使用 Pavel Anossov(现已删除)的评论:
class met(type):
def __init__(cls, name, bases, dct):
super(met, cls).__init__(name, bases, dct)
cls._test_member = "test_value"
object = met('object', (object,), {})
class A(object):
pass
print(A._test_member)
印刷
test_value
请注意,一个类只能有一个元类。(毕竟,任何对象都只能有一种类型)。但此外,一个类的元类必须是其所有基类的元类的(非严格)子类。换句话说,类的元类和它的所有基类的元类必须相同,或者所有这些元类必须是彼此的子类。因此,如果一个类尝试使用不是met
.
例如,
class met(type):
def __init__(cls, name, bases, dct):
super(met, cls).__init__(name, bases, dct)
cls._test_member = "test_value"
object = met('object', (object,), {})
class someothertype(type): pass
class B(object):
__metaclass__ = someothertype
提高
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases