转载地址:http://blog.jobbole.com/21351/
Stack Overflow上的好文:https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python
另外有几点理解记录下:
创建一个实例时,有时会传入参数,这些参数会同时传入 __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 in attr) # 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__
方法使用三个实参构造一个类对象出来