python面試題之Python如何實現單例模式?

2021-09-26 18:42:35 字數 1569 閱讀 7108

#使用__metaclass__(元類)的高階python用法  

class singleton2(type):

def __init__(cls, name, bases, dict):

super(singleton2, cls).__init__(name, bases, dict)

cls._instance = none

def __call__(cls, *args, **kw):

if cls._instance is none:

cls._instance = super(singleton2, cls).__call__(*args, **kw)

return cls._instance

class myclass3(object):

__metaclass__ = singleton2

one = myclass3()

two = myclass3()

two.a = 3

print one.a

#3

print id(one)

#31495472

print id(two)

#31495472

print one == two

#true

print one is two

#true

#使用裝飾器(decorator),

#這是一種更pythonic,更elegant的方法,

#單例類本身根本不知道自己是單例的,因為他本身(自己的**)並不是單例的

def singleton(cls, *args, **kw):

instances = {}

def _singleton():

if cls not in instances:

instances[cls] = cls(*args, **kw)

return instances[cls]

return _singleton

@singleton

class myclass4(object):

a = 1

def __init__(self, x=0):

self.x = x

one = myclass4()

two = myclass4()

two.a = 3

print one.a

#3

print id(one)

#29660784

print id(two)

#29660784

print one == two

#true

print one is two

#true

one.x = 1

print one.x

#1

print two.x

#1本文首發於python黑洞網,csdn同步跟新

python語法面試題 python面試題

1.去重,集合 集合的乙個重要特點是 自動去除重複的值 li 1,2,3,1,1,2,2,3,3 去除重複的元素 set set li 轉換為集合,因為集合會自動去重。print set li list set 將集合轉換為列表print li 2.生成器 規則 生成器函式,或者生成器表示式,在呼叫...

C 面試題之i 面試題

i 面試題1.cpp 中國台灣某著名防毒軟體公司2005年10月面試題 int i 3,j 4 i?i j printf d d n i,j a.3 3 b.4 4 c.3 4 d.4 3 答案b i 面試題2.cpp 中國某著名計算機金融軟公司2005年面試題 int x 1,j 2 int k ...

C 面試題之sizeof面試題

sizeof面試題1.cpp what is the output of the following code?美國某著名計算機軟硬體公司面試題 include include include using namespace std structa structb int main 解析 ss1是乙...