metaclass 了解一下

Posted 拜悦神教

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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__

以上是关于metaclass 了解一下的主要内容,如果未能解决你的问题,请参考以下文章

深刻理解Python中的元类(metaclass)

深刻理解Python中的元类(metaclass)

深刻理解Python中的元类(metaclass)

深刻理解Python中的元类(metaclass)

哇, Six.with_metaclass() 有效吗?

深刻理解Python中的元类(metaclass)以及元类实现单例模式