PEP 3115有以下使用__prepare__元類方法的示例(print陳述句是我的):
# The custom dictionary
class member_table(dict):
def __init__(self):
self.member_names = []
def __setitem__(self, key, value):
print(f'in __setitem__{key, value}')
# if the key is not already defined, add to the
# list of keys.
if key not in self:
self.member_names.append(key)
# Call superclass
dict.__setitem__(self, key, value)
# The metaclass
class OrderedClass(type):
# The prepare function
@classmethod
def __prepare__(metacls, name, bases): # No keywords in this case
print('in __prepare__')
return member_table()
# The metaclass invocation
def __new__(cls, name, bases, classdict):
print('in __new__')
# Note that we replace the classdict with a regular
# dict before passing it to the superclass, so that we
# don't continue to record member names after the class
# has been created.
result = type.__new__(cls, name, bases, dict(classdict))
result.member_names = classdict.member_names
return result
print('before MyClass')
class MyClass(metaclass=OrderedClass):
print('in MyClass 1')
# method1 goes in array element 0
def method1(self):
pass
print('in MyClass 2')
# method2 goes in array element 1
def method2(self):
pass
print('in MyClass 3')
運行這個,列印這個:
before MyClass
in __prepare__
in __setitem__('__module__', '__main__')
in __setitem__('__qualname__', 'MyClass')
in MyClass 1
in __setitem__('method1', <function MyClass.method1 at 0x7fa70414da60>)
in MyClass 2
in __setitem__('method2', <function MyClass.method2 at 0x7fa70414daf0>)
in MyClass 3
in __new__
因此,似乎在MyClass執行時,執行首先轉到類的元類__prepare__方法,該方法回傳member_table()(誰/什么使用此回傳值?),然后設定類的__module__and __qualname__,然后執行類主體,該方法設定類的方法(method1和method2) ,然后__new__使用回傳值__prepare__作為classdict引數值呼叫該方法__new__(誰/什么正在傳遞這個值?)。
我試圖在 thonny 的除錯器中逐步執行,但這引發了錯誤。我還嘗試在 pythontutor.com 中逐步執行,但這不夠細化。我pdb'編輯了它,但很難理解發生了什么。最后,我添加了一些print陳述句,它們出現在上面的代碼中。
uj5u.com熱心網友回復:
的結果prepare()是namespace傳遞給的引數__new__。它是評估類主體的命名空間。
因此,新創建的類中,你可以看到的價值MyClass.__module__,MyClass.__qualname__等等,因為它們是在的命名空間物件被分配MyClass。
元類的大多數用途都不需要prepare(),而是使用普通的命名空間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352046.html
上一篇:C 向下轉換物件的奇怪行為
下一篇:矩陣類記憶體分配和多載
