學習筆記01 單例和元類

2021-08-25 16:57:53 字數 1749 閱讀 5628

參考個人覺得講解的很透徹。

元類是乙個類的類,該類是它的元類的乙個例項。類的定義由它的元類決定,所以我們用類a建立乙個類時,python通過呼叫a=type(name, bases, dict)建立它,name--類的名字,bases--基類,dict--屬性變數。如下兩段**,其實作用一樣。

# 建立乙個hello類,擁有屬性say_hello

class hello():

def say_hello(self, name='world'):

print('hello, %s.' % name)

# 從hello類建立乙個例項hello

hello = hello()

# 使用hello呼叫方法say_hello

hello.say_hello()

def fn(self, name='world'): # 假如我們有乙個函式叫fn

print('hello, %s.' % name)

hello = type('hello', (object,), dict(say_hello=fn)) # 通過type建立hello class

# 從hello類建立乙個例項hello

hello = hello()

# 使用hello呼叫方法say_hello

hello.say_hello()

python3.5中的乙個示例元類的實現:

class myint(type):

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

print('***** here is my int *****', args)

print('now do whatever you want with these objects...')

return type.__call__(cls, *args, **kwds)

class int(metaclass=myint):

def __init__(self, x, y):

self.x = x

self.y = y

i = int(3, 5)

以上**說明,對於已存在的類來說,當需要建立物件時,將呼叫python的特殊方法__call__,意味著現在元類控制著物件的例項化

以上思路說明元類對類建立和物件例項化有更多的控制權,所以可以用於建立單例。以下**為單例的元類實現。

class metasingleton(type):

_instances = {}

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

if cls not in cls._instances:

cls._instances[cls] = super(metasingleton, cls).__call__(*args, **kwargs)

return cls._instances[cls]

class logger(metaclass=metasingleton):

pass

if __name__ == '__main__':

logger1 = logger()

logger2 =logger()

print(logger1)

print(logger2) # same address

python元類單例 元類實現單例模式

python中的類也是物件。元類就是用來建立這些類 物件 的,元類就是類的類,你可以這樣理解為 myclass metaclass 元類建立 myobject myclass 類建立例項 實際上myclass就是通過type 來創建立出myclass類,它是type 類的乙個例項 同時myclass...

Python學習記錄(元類和單例模式)

在看原始碼的時候發現如下的單例模式,一開始不能理解。看了幾篇部落格後慢慢理解了。這裡簡單描述下我的理解。其中比較重要的一點是要記住類是元類的例項。class singleton type def init cls,name,bases,dict super singleton,cls init na...

元類實現單例

單例1 元類的單例 1 import settings23 4class mymeat type 5呼叫 init 得到mysql呼叫之前的時候就有乙個預設的例項化的結果 6def init self,class name,class bases,class dic 7建立乙個初始化的物件,並把這個...