深刻理解Python中的元類(metaclass)(轉)
阿新 • • 發佈:2019-04-20
pytho light turn 理解 war highlight 參數 實例化 type
轉載地址:http://blog.jobbole.com/21351/
另外有幾點理解記錄下:
創建一個實例時,有時會傳入參數,這些參數會同時傳入 __init__() 和 __new__(),如:
class Teacher(object): def __init__(self, *args, **kwargs): print("enter __init__") print(args) def __new__(cls, *args, **kwargs): print("enter __new__") print(args) return super(Teacher, cls).__new__(cls) wang = Teacher(‘xiaohong‘, ‘xiaoming‘) 打印結果: enter __new__ (‘xiaohong‘, ‘xiaoming‘) enter __init__ (‘xiaohong‘, ‘xiaoming‘)
所以在如下代碼中
class UpperAttrMetaclass(type): def __new__(cls, future_class_name, future_class_parents, future_class_attr): attr = ((name, value) for name, value in future_class_attr.items() if not name.startswith(‘__‘)) uppercase_attr = dict((name.upper(), value) for name, value inattr) # return super(UpperAttrMetaclass, cls).__new__(cls, future_class_name, future_class_parents, uppercase_attr) return type(future_class_name, future_class_parents, uppercase_attr) Foo2 = UpperAttrMetaclass(‘Foo2‘, (), {‘bar‘: ‘bip‘}) print(Foo2.BAR) 結果:bip
Foo2 = UpperAttrMetaclass(‘Foo2‘, (), {‘bar‘: ‘bip‘})實例化一個類對象時,三個參數實際也傳給了__new__ ,之前一直以為實例化對象時傳進的參數只能是 __init__方法接收,
看來理解是不對的,所以使用type(future_class_name, future_class_parents, uppercase_attr)創建一個類時,三個參數也應該是傳遞給了type的__new__方法,這樣才能通過__new__
方法使用三個實參構造一個類對象出來
深刻理解Python中的元類(metaclass)(轉)