Python(metaclass)

示例代码


class A(type):
    @classmethod
    def __prepare__(cls, name, bases, **kwds):
        # 返回一个字典作为__new__里的namespace
        return {
            '__init__': lambda self, i: print(i)
        }

    def __new__(cls, name, bases, namespace, **kwds):
        # namespace包含了类的属性和方法
        # 此时修改namespace依旧会影响类的结构
        return type.__new__(cls, name, bases, namespace)

    def __init__(self, name, bases, namespace, **kwds):
        # 此时修改namespace将不会影响类的结构
        # 可以通过self来修改
        self.echo = lambda self, i: print(i)

class B(metaclass=A):
    pass

b = B('hello')
b.echo('world')

参考


  • Customizing class creation
  • Basic customization

你可能感兴趣的:(Python(metaclass))