Skip to content

Instantly share code, notes, and snippets.

@geekKeen
Created July 22, 2017 11:49
Show Gist options
  • Save geekKeen/0c467025563f6f4cc0c46c3c6362cd16 to your computer and use it in GitHub Desktop.
Save geekKeen/0c467025563f6f4cc0c46c3c6362cd16 to your computer and use it in GitHub Desktop.
class Meta(type):
def __init__(cls, classname, base, fields):
super(Meta, cls).__init__(classname,base, fields)
print cls, classname, base, fields # <class A>, A, <type object>, {...., '__init__': function<...>}
class A(object):
__metaclass__ = Meta
def __init__(self):
pass
class Meta1(type):
def __new__(cls, classname, base, fields):
print cls, classname, base, fields # <class Meta1>, B, <type object>, {..., '__init__': function<...>}
super(Meta, cls).__init__(classname,base, fields)
class B(object):
__metaclass__ = Meta1
def __init__(self):
pass
if __name__ == "__main__":
a = A()
b = B()
@geekKeen
Copy link
Author

  1. 元类的用法, 可以控制类的创建和实例化
  2. 使用元类时的 __init__ / __new__ 的区别, 第一个参数 cls 指向的是不同对象 __init__ 中指的是已经创建好的类, 而 __new__ 则是 Meta类
  3. 传入的参数需要注意, 包括base, fields, fields

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment