Python进阶:一步步理解Python中的元类metaclass

  • 确定类Foo的父类是否有参数metaclass,如果没有则:
  • 确定类Foo的父类的父类是否有参数metaclass,如果没有则:
  • 使用默认元类type(type的用法会在3中讲解)。
  • 上边的例子中,前三项都不符合,则直接使用默认元类type。即上边的语句相当于:

    def hello(self):    print("hello world")    returnFoo = type("Foo", (object,), {"hello": hello})

    此时可以看出,实际上类Foo是元类type的实例。参见文章的封面图。

    3. 动态创建类

    Python中的类可以动态创建,用的就是默认元类type。动态创建类的type函数原型为:

    type(object_or_name, bases, dict)

    这里不过多赘述,上个章节中有介绍。举个比较复杂的动态创建类的例子:

    def init(self, name):    self.name = namereturndef hello(self):print("hello %s" % self.name)returnFoo = type("Foo", (object,), {"__init__": init, "hello": hello, "cls_var": 10})foo = Foo(