metaclass 了解一下

创建类的两种方式

方式一:
class Foo(object,metaclass=type):
    CITY = "bj"

    def func(self,x):
        return x + 1
方式二:
Foo = type('Foo',(object,),{'CITY':'bj','func':lambda self,x:x+1})

类的演变

演变1:
class MyType(type):
    def __init__(self,*args,**kwargs):
        print('创建类之前')
        super(MyType,self).__init__(*args,**kwargs)
        print('创建类之后')

Base = MyType('Base',(object,),{})
# class Base(object,metaclass=MyType):
#     pass

class Foo(Base):
    CITY = "bj"
    def func(self, x):
        return x + 1
演变2:
class MyType(type):
    def __init__(self,*args,**kwargs):
        print('创建类之前')
        super(MyType,self).__init__(*args,**kwargs)
        print('创建类之后')

def with_metaclass(arg):
    return MyType('Base',(arg,),{}) # class Base(object,metaclass=MyType): pass

class Foo(with_metaclass(object)):
    CITY = "bj"
    def func(self, x):
        return x + 1

演变3:
class MyType(type):
    def __init__(self,*args,**kwargs):
        super(MyType,self).__init__(*args,**kwargs)

class Foo(object,metaclass=MyType): 

总结

1. 默认类由type实例化创建。
2. 某个类指定metaclass=MyType,那么当前类的所有派生类都由于MyType创建。
3. 实例化对象
    - type.__init__         
    - type.__call__
    - 类.__new__
    - 类.__init__

猜你喜欢

转载自www.cnblogs.com/iyouyue/p/8981983.html