"""metaclass的作用是指定当前类由谁来创建""" # 第一种创建类的方式 class Foo(object): name = "小强" # 类的静态字段 def func(self): return 666 val = Foo() print(val.name) # 第二种创建类的方式 Foo1 = type("Foo", (object,), {"name": "小强", "func": lambda self: 666}) val1 = Foo1() print(val1.name) # 2.自定义type class YouType(type): pass class Foo2(object, metaclass=YouType): # metaclass指定当前继承类 name = "小老鼠" def func(self): return "猫不抓" val2 = Foo2() print(val2.name) Foo3 = YouType("Foo", (object,), {"name": "小老鼠", "func": lambda self: "猫不抓"}) val3 = Foo3() print(val3.name) # 3.metaclass class MyType(type): def __init__(self, *args, **kwargs): super(MyType, self).__init__(*args, **kwargs) def __call__(cls, *args, **kwargs): obj = cls.__new__(cls) cls.__init__(obj, *args, **kwargs) return obj class Foo4(object, metaclass=MyType): name = "旺财" def __init__(self): pass def __new__(cls, *args, **kwargs): return object.__new__(cls) def func(self): return 666 # Foo4是MyType的一个对象 obj = Foo4() print(obj.name)