码迷,mamicode.com
首页 > Web开发 > 详细

metaclass 了解一下

时间:2018-05-02 20:53:41      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:rgs   foo   super   ret   pass   实例化   *args   war   pre   

创建类的两种方式

方式一:
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 了解一下

标签:rgs   foo   super   ret   pass   实例化   *args   war   pre   

原文地址:https://www.cnblogs.com/iyouyue/p/8981983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!