Python中的元类是什么?

7323

什么是元类?它们有什么用途?

25个回答

8938

类作为对象

在深入研究元类之前,对Python类有扎实的理解是有益的。Python对类有一个特别独特的概念,它借鉴自Smalltalk语言。

在大多数语言中,类只是描述如何生成对象的代码片段。在Python中也有一定的道理:

>>> class ObjectCreator(object):
...       pass

>>> my_object = ObjectCreator()
>>> print(my_object)
<__main__.ObjectCreator object at 0x8974f2c>

但在Python中,类不仅仅是如此。 类也是对象。

是的,对象。

当Python脚本运行时,每一行代码都会从上到下执行。当Python解释器遇到class关键字时,Python根据后面的类的“描述”创建一个对象。因此,以下指令

>>> class ObjectCreator(object):
...       pass

...创建一个名为ObjectCreator的对象!
这个对象(类)本身能够创建对象(称为实例)。
但是,它仍然是一个对象。因此,像所有的对象一样:
  • 你可以将它赋值给一个变量1
    JustAnotherVariable = ObjectCreator
    
  • 你可以给它附加属性
    ObjectCreator.class_attribute = 'foo'
    
  • 你可以将它作为函数参数传递
    print(ObjectCreator)
    
注意,仅仅将其赋值给另一个变量并不会改变类的`__name__`,也就是说,
>>> print(JustAnotherVariable)
<class '__main__.ObjectCreator'>

>>> print(JustAnotherVariable())
<__main__.ObjectCreator object at 0x8997b4c>

动态创建类

由于类也是对象,您可以像创建其他对象一样随时创建它们。

首先,您可以在函数中使用class来创建一个类:

>>> def choose_class(name):
...     if name == 'foo':
...         class Foo(object):
...             pass
...         return Foo # return the class, not an instance
...     else:
...         class Bar(object):
...             pass
...         return Bar
...
>>> MyClass = choose_class('foo')
>>> print(MyClass) # the function returns a class, not an instance
<class '__main__.Foo'>
>>> print(MyClass()) # you can create an object from this class
<__main__.Foo object at 0x89c6d4c>

但这并不是很动态,因为你仍然需要自己编写整个类。
由于类是对象,它们必须由某些东西生成。
当你使用class关键字时,Python会自动创建这个对象。但是,像Python中的大多数事物一样,它也给了你手动完成的方式。
还记得函数type吗?那个让你知道一个对象是什么类型的好老函数:
>>> print(type(1))
<type 'int'>
>>> print(type("1"))
<type 'str'>
>>> print(type(ObjectCreator))
<type 'type'>
>>> print(type(ObjectCreator()))
<class '__main__.ObjectCreator'>

嗯, type 也有完全不同的能力:它可以即时创建类。 type 可以接受一个类的描述作为参数,并返回一个类。

(我知道,根据传递给它的参数,同一个函数可以有两个完全不同的用途,这听起来有些愚蠢。这是 Python 中由于向后兼容性而引起的问题)

type 的工作方式如下:

type(name, bases, attrs)

在哪里:

  • name: 类的名称
  • bases: 父类的元组(用于继承,可以为空)
  • attrs: 包含属性名称和值的字典

e.g.:

>>> class MyShinyClass(object):
...       pass

可以通过手动方式创建如下:
>>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object
>>> print(MyShinyClass)
<class '__main__.MyShinyClass'>
>>> print(MyShinyClass()) # create an instance with the class
<__main__.MyShinyClass object at 0x8997cec>

您会注意到我们使用 MyShinyClass 作为类的名称和保存类引用的变量。它们可以不同,但没有必要让事情复杂化。 type 接受一个字典来定义类的属性。因此:
>>> class Foo(object):
...       bar = True

可以翻译为:
>>> Foo = type('Foo', (), {'bar':True})

并且作为一个普通的类使用:

>>> print(Foo)
<class '__main__.Foo'>
>>> print(Foo.bar)
True
>>> f = Foo()
>>> print(f)
<__main__.Foo object at 0x8a9b84c>
>>> print(f.bar)
True

当然,你可以继承它,所以:
>>>   class FooChild(Foo):
...         pass

会是:

>>> FooChild = type('FooChild', (Foo,), {})
>>> print(FooChild)
<class '__main__.FooChild'>
>>> print(FooChild.bar) # bar is inherited from Foo
True

最终,你会想要在你的类中添加方法。只需定义一个具有正确签名的函数,并将其分配为属性即可。
>>> def echo_bar(self):
...       print(self.bar)
...
>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})
>>> hasattr(Foo, 'echo_bar')
False
>>> hasattr(FooChild, 'echo_bar')
True
>>> my_foo = FooChild()
>>> my_foo.echo_bar()
True

并且在动态创建类之后,您可以添加更多的方法,就像向通常创建的类对象添加方法一样。
>>> def echo_bar_more(self):
...       print('yet another method')
...
>>> FooChild.echo_bar_more = echo_bar_more
>>> hasattr(FooChild, 'echo_bar_more')
True

你看到我们正在做什么:在Python中,类是对象,你可以动态地创建一个类。
这就是当你使用关键字"class"时,Python所做的事情,它通过使用元类来实现。
元类是创建类的"东西"。
你定义类是为了创建对象,对吧?
但是我们学到了Python的类也是对象。
嗯,元类就是创建这些对象的东西。它们是类的类,你可以这样想象它们:
MyClass = MetaClass()
my_object = MyClass()

你已经看到了,type让你可以做这样的事情:
MyClass = type('MyClass', (), {})

这是因为函数type实际上是一个元类。在Python中,type是用来在幕后创建所有类的元类。
现在你可能会想,“为什么它要小写,而不是Type呢?”
嗯,我猜这是为了与创建字符串对象的str类和创建整数对象的int类保持一致。type只是创建类对象的类。
通过检查__class__属性,你可以看到这一点。
在Python中,每个东西,我是说每个东西,都是一个对象。这包括整数、字符串、函数和类。它们都是对象。而且它们都是从一个类创建的:
>>> age = 35
>>> age.__class__
<type 'int'>
>>> name = 'bob'
>>> name.__class__
<type 'str'>
>>> def foo(): pass
>>> foo.__class__
<type 'function'>
>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__
<class '__main__.Bar'>

现在,任何__class____class__是什么?
>>> age.__class__.__class__
<type 'type'>
>>> name.__class__.__class__
<type 'type'>
>>> foo.__class__.__class__
<type 'type'>
>>> b.__class__.__class__
<type 'type'>

所以,元类就是创建类对象的东西。
如果你愿意,你可以称之为“类工厂”。
`type` 是Python使用的内置元类,但当然,你也可以创建自己的元类。

__metaclass__ 属性

在Python 2中,当你编写一个类时,你可以添加一个 `__metaclass__` 属性(有关Python 3语法,请参见下一节):
class Foo(object):
    __metaclass__ = something...
    [...]

如果你这样做,Python将使用元类来创建类Foo
小心,这有点棘手。
你首先写class Foo(object),但是类对象Foo还没有在内存中创建。
Python会在类定义中查找__metaclass__。如果找到了,它将使用它来创建对象类Foo。如果没有找到,它将使用type来创建类。
多读几遍。
当你执行以下操作时:
class Foo(Bar):
    pass

Python做了以下几件事情:
在`Foo`中是否有`__metaclass__`属性?
如果有,就在内存中创建一个类对象(我说的是类对象,跟着我来),使用`__metaclass__`中的内容来命名为`Foo`的类对象。
如果Python找不到`__metaclass__`,它会在模块级别寻找`__metaclass__`,并尝试做同样的事情(但只适用于没有继承任何东西的类,基本上是旧式类)。
然后,如果找不到任何`__metaclass__`,它将使用`Bar`(第一个父类)自己的元类(可能是默认的`type`)来创建类对象。

在这里要注意的是,__metaclass__ 属性不会被继承,而是继承父类 (Bar.__class__) 的元类。如果 Bar 使用了一个使用 type() (而不是 type.__new__()) 创建 Bar__metaclass__ 属性,那么子类将不会继承该行为。

现在的重要问题是,你可以在 __metaclass__ 中放置什么?

答案是能够创建一个类的东西。

那么什么可以创建一个类呢?type,或者任何继承或使用它的东西。

Python 3 中的元类

在 Python 3 中,设置元类的语法已经改变:

class Foo(object, metaclass=something):
    ...

__metaclass__属性不再使用,而是采用基类列表中的关键字参数。

然而,元类的行为基本保持不变

Python 3中为元类添加的一项功能是您还可以将属性作为关键字参数传递给元类,例如:

class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2):
    ...

阅读下面的部分以了解Python如何处理此问题。

自定义元类

元类的主要目的是在创建类时自动更改该类。

通常,您会在API中这样做,即希望创建与当前上下文匹配的类。

想象一个愚蠢的例子,您决定模块中的所有类的属性都应以大写形式编写。有几种方法可以实现这一点,但一种方法是在模块级别设置__metaclass__

这样,该模块的所有类将使用此元类创建,并且我们只需告诉元类将所有属性转换为大写。

幸运的是,__metaclass__实际上可以是任何可调用对象,不一定是一个正式的类(我知道,名称中带有'类'的东西不需要是一个类,颇有些讽刺...但它很有用)。

因此,我们将从一个简单的例子开始,使用一个函数。

# the metaclass will automatically get passed the same argument
# that you usually pass to `type`
def upper_attr(future_class_name, future_class_parents, future_class_attrs):
    """
      Return a class object, with the list of its attribute turned
      into uppercase.
    """
    # pick up any attribute that doesn't start with '__' and uppercase it
    uppercase_attrs = {
        attr if attr.startswith("__") else attr.upper(): v
        for attr, v in future_class_attrs.items()
    }

    # let `type` do the class creation
    return type(future_class_name, future_class_parents, uppercase_attrs)

__metaclass__ = upper_attr # this will affect all classes in the module

class Foo(): # global __metaclass__ won't work with "object" though
    # but we can define __metaclass__ here instead to affect only this class
    # and this will work with "object" children
    bar = 'bip'

让我们检查一下:

>>> hasattr(Foo, 'bar')
False
>>> hasattr(Foo, 'BAR')
True
>>> Foo.BAR
'bip'

现在,让我们完全相同的方式来做,但是使用一个真正的类作为元类:
# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
    # __new__ is the method called before __init__
    # it's the method that creates the object and returns it
    # while __init__ just initializes the object passed as parameter
    # you rarely use __new__, except when you want to control how the object
    # is created.
    # here the created object is the class, and we want to customize it
    # so we override __new__
    # you can do some stuff in __init__ too if you wish
    # some advanced use involves overriding __call__ as well, but we won't
    # see this
    def __new__(upperattr_metaclass, future_class_name,
                future_class_parents, future_class_attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in future_class_attrs.items()
        }
        return type(future_class_name, future_class_parents, uppercase_attrs)

让我们重新编写上面的代码,但使用更短和更实际的变量名,现在我们知道它们的含义了:
class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return type(clsname, bases, uppercase_attrs)

你可能注意到了额外的参数cls。这没有什么特别之处:无论何时,__new__总是接收所定义的类作为第一个参数。就像普通方法中的self表示接收实例作为第一个参数一样,或者类方法中的定义类。
但这不符合面向对象编程的规范。我们直接调用了type,而没有覆盖或调用父类的__new__方法。让我们来改正这个问题吧:
class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return type.__new__(cls, clsname, bases, uppercase_attrs)

我们可以通过使用super来使其更加简洁,这将简化继承(因为是的,你可以有元类,从元类继承,再从类型继承)。
class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }

        # Python 2 requires passing arguments to super:
        return super(UpperAttrMetaclass, cls).__new__(
            cls, clsname, bases, uppercase_attrs)

        # Python 3 can use no-arg super() which infers them:
        return super().__new__(cls, clsname, bases, uppercase_attrs)

哦,在Python 3中,如果你使用关键字参数调用它,就像这样:
class Foo(object, metaclass=MyMetaclass, kwarg1=value1):
    ...

在元类中使用它时,它的翻译如下:
class MyMetaclass(type):
    def __new__(cls, clsname, bases, dct, kwargs1=default):
        ...

那就是这样了。关于元类,实际上没有更多的内容了。
使用元类编写的代码复杂的原因并不是因为元类本身,而是因为通常会使用元类来进行一些扭曲的操作,依赖于内省、继承的操作,以及像`__dict__`等变量的操作。
确实,元类特别适用于进行黑魔法和复杂的操作。但是从它们自身来说,它们很简单:
- 拦截类的创建 - 修改类 - 返回修改后的类
为什么要使用元类而不是函数呢?
既然`__metaclass__`可以接受任何可调用对象,为什么要使用类呢?毕竟类显然更加复杂。
有几个原因可以这样做:
意图很明确。当你读到UpperAttrMetaclass(type)时,你知道接下来会发生什么。
你可以使用面向对象编程。元类可以继承自元类,覆盖父类方法。甚至可以使用元类的元类。
如果你指定了一个元类类,那么类的子类将成为其元类的实例,但如果是元类函数,则不会。
你可以更好地组织你的代码。你从不会像上面的例子那样使用元类来处理琐碎的事情。通常它用于处理复杂的问题。能够创建多个方法并将它们分组在一个类中非常有用,可以使代码更易读。
你可以挂钩__new____init____call__。这将允许你做不同的事情,即使通常你可以在__new__中完成所有操作,但有些人更喜欢使用__init__
这些被称为元类,该死!它一定有意义!

为什么要使用元类?

现在是个大问题。为什么要使用一些晦涩难懂且容易出错的特性呢?

嗯,通常你不会使用:

元类是深层魔法,99%的用户不需要担心它。如果你想知道是否需要它们,那就不需要(真正需要它们的人肯定知道他们需要它们,并且不需要解释为什么需要)。
Python大师Tim Peters
元类的主要用途是创建API。一个典型的例子是Django ORM。它允许你定义如下内容:
class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

但是如果你这样做:
person = Person(name='bob', age='35')
print(person.age)

它不会返回一个IntegerField对象。它将返回一个int,并且甚至可以直接从数据库中获取。
这是可能的,因为models.Model定义了__metaclass__并使用一些魔法将你刚刚用简单语句定义的Person转化为与数据库字段相关的复杂钩子。
Django通过暴露简单的API并使用元类来重新创建代码,使得复杂的事情看起来很简单,在幕后完成真正的工作。
最后的结论
首先,你知道类是可以创建实例的对象。
事实上,类本身也是元类的实例。
>>> class Foo(object): pass
>>> id(Foo)
142630324

在Python中,一切都是对象,它们要么是类的实例,要么是元类的实例。
除了typetype实际上是它自己的元类。这不是你可以在纯Python中复制的东西,而是通过在实现层面上稍微作弊来实现的。
其次,元类很复杂。对于非常简单的类修改,您可能不想使用它们。您可以使用两种不同的技术来更改类: 99%的情况下,您需要进行类修改时,最好使用这些方法。
但98%的时间,您根本不需要进行类修改。

76
在 Django 的 models.Model 中,似乎没有使用 __metaclass__,而是使用 class Model(metaclass=ModelBase): 来引用一个名为 ModelBase 的类,这个类在内部实现了元类的魔法。非常棒的文章!以下是 Django 源代码链接:https://github.com/django/django/blob/master/django/db/models/base.py#L382 - Max Goodridge
35
请注意,这里的 __metaclass__ 属性不会被继承,而是会继承父类 (Bar.__class__) 的元类。如果 Bar 使用了一个通过 type() 而非 type.__new__() 创建 Bar__metaclass__ 属性,子类将不会继承该行为。 - petrux
35
@MaxGoodridge 这是用于元类的Python 3语法。请参阅Python 3.6数据模型,与Python 2.7数据模型相比。 - TBBle
29
你现在想知道为什么它用小写字母而不是大写字母来书写——这是因为它是用C实现的。这也是为什么defaultdict是小写字母,而OrderedDict(在Python 2中)则是普通的CamelCase。 - Mr_and_Mrs_D
34
这是一个社区维基答案(因此,那些提供更正/改进意见的人可能会考虑将他们的评论编辑到答案中,如果他们确定这些更正是正确的)。 - Brōtsyorfuzthrāx
显示剩余19条评论

3426

元类是类的类。类定义了类的实例(即对象)的行为,而元类定义了类的行为。类是元类的一个实例。

在Python中,您可以使用任意可调用对象作为元类(如Jerub所示),但更好的方法是将其作为一个实际的类本身。 type是Python中通常的元类。 type本身就是一个类,也是它自己的类型。您无法纯粹地在Python中重新创建像 type 这样的东西,但Python会有一些小技巧。在Python中创建自己的元类,您只需要继承 type

元类最常用作类工厂。当您通过调用类来创建对象时,Python通过调用元类(执行“class”语句时)创建一个新类。与普通的 __init__ __new__ 方法结合使用,元类允许您在创建类时做“额外的事情”,例如将新类注册到某个注册表中,或者完全替换该类。

当执行 class 语句时,Python首先按照正常的代码块方式执行 class 语句的主体。生成的名称空间(一个字典)持有将要创建的类的属性。通过查看将要创建的类的基类(元类是继承的), __metaclass__ 属性(如果有),或 __metaclass__ 全局变量来确定元类。然后使用类的名称、基类和属性调用元类以实例化它。

但是,元类实际上定义了类的类型,而不仅仅是类的工厂,因此您可以用它们做更多的事情。例如,您可以在元类上定义普通方法。这些元类方法与classmethods类似,因为它们可以在没有实例的情况下对类进行调用,但它们也不像classmethods类似,因为不能在类的实例上调用它们。type.__subclasses__() type 元类上的一个方法示例。您还可以定义正常的“magic”方法,如 __add__ __iter__ __getattr__ ,以实现或更改类的行为方式。

以下是各个部分的聚合示例:

def make_hook(f):
    """Decorator to turn 'foo' method into '__foo__'"""
    f.is_hook = 1
    return f

class MyType(type):
    def __new__(mcls, name, bases, attrs):

        if name.startswith('None'):
            return None

        # Go over attributes and see if they should be renamed.
        newattrs = {}
        for attrname, attrvalue in attrs.iteritems():
            if getattr(attrvalue, 'is_hook', 0):
                newattrs['__%s__' % attrname] = attrvalue
            else:
                newattrs[attrname] = attrvalue

        return super(MyType, mcls).__new__(mcls, name, bases, newattrs)

    def __init__(self, name, bases, attrs):
        super(MyType, self).__init__(name, bases, attrs)

        # classregistry.register(self, self.interfaces)
        print "Would register class %s now." % self

    def __add__(self, other):
        class AutoClass(self, other):
            pass
        return AutoClass
        # Alternatively, to autogenerate the classname as well as the class:
        # return type(self.__name__ + other.__name__, (self, other), {})

    def unregister(self):
        # classregistry.unregister(self)
        print "Would unregister class %s now." % self

class MyObject:
    __metaclass__ = MyType


class NoneSample(MyObject):
    pass

# Will print "NoneType None"
print type(NoneSample), repr(NoneSample)

class Example(MyObject):
    def __init__(self, value):
        self.value = value
    @make_hook
    def add(self, other):
        return self.__class__(self.value + other.value)

# Will unregister the class
Example.unregister()

inst = Example(10)
# Will fail with an AttributeError
#inst.unregister()

print inst + inst
class Sibling(MyObject):
    pass

ExampleSibling = Example + Sibling
# ExampleSibling is now a subclass of both Example and Sibling (with no
# content of its own) although it will believe it's called 'AutoClass'
print ExampleSibling
print ExampleSibling.__mro__

19
class A(type):pass class B(type, metaclass=A):pass b.class = b翻译: 类A(type):无操作 类B(type,metaclass = A):无操作 b.class = b - pppery
36
ppperry显然是指你不能在不使用类型本身作为元类的情况下重新创建类型。这是说得通的。 - Holle van
6
Example类的实例应该调用unregister()方法吗? - Ciasto piekarz
22
注意,在Python 3中不支持__metaclass__。在Python 3中使用class MyObject(metaclass=MyType),参见https://www.python.org/dev/peps/pep-3115/和下面的答案。 - BlackShift
6
该文档描述了如何选择元类。元类不是被继承,而是被派生的。如果您指定了一个元类,它必须是每个基类元类的子类型;否则,您将使用一个基类元类,它是每个其他基类元类的子类型。请注意,有可能找不到任何有效的元类,此时定义将失败。 - chepner
显示剩余5条评论

490

注意,这个答案是针对Python 2.x的,因为它是在2008年写的,在3.x中元类略有不同。

元类是使“类”工作的秘密配方。新型对象默认的元类被称为“type”。

class type(object)
  |  type(object) -> the object's type
  |  type(name, bases, dict) -> a new type

元类需要3个参数,分别是'name'、'bases'和'dict'。

这里有个秘密。在这个示例类定义中查找名字(name)、基类(bases)和字典(dict)的来源。

class ThisIsTheName(Bases, Are, Here):
    All_the_code_here
    def doesIs(create, a):
        dict

让我们定义一个元类,展示如何通过 'class:' 调用它。

def test_metaclass(name, bases, dict):
    print 'The Class Name is', name
    print 'The Class Bases are', bases
    print 'The dict has', len(dict), 'elems, the keys are', dict.keys()

    return "yellow"

class TestName(object, None, int, 1):
    __metaclass__ = test_metaclass
    foo = 1
    def baz(self, arr):
        pass

print 'TestName = ', repr(TestName)

# output => 
The Class Name is TestName
The Class Bases are (<type 'object'>, None, <type 'int'>, 1)
The dict has 4 elems, the keys are ['baz', '__module__', 'foo', '__metaclass__']
TestName =  'yellow'

现在,我们来看一个真正有意义的示例。这将自动使列表"attributes"中的变量设置为该类上,并设置为None。

def init_attributes(name, bases, dict):
    if 'attributes' in dict:
        for attr in dict['attributes']:
            dict[attr] = None

    return type(name, bases, dict)

class Initialised(object):
    __metaclass__ = init_attributes
    attributes = ['foo', 'bar', 'baz']

print 'foo =>', Initialised.foo
# output=>
foo => None

请注意,Initialised 元类通过拥有 init_attributes 元类获得的神奇行为不会传递到 Initialised 的子类。

下面是一个更具体的示例,展示了如何子类化 'type' 来创建一个在类被创建时执行操作的元类。这相当棘手:

class MetaSingleton(type):
    instance = None
    def __call__(cls, *args, **kw):
        if cls.instance is None:
            cls.instance = super(MetaSingleton, cls).__call__(*args, **kw)
        return cls.instance

class Foo(object):
    __metaclass__ = MetaSingleton

a = Foo()
b = Foo()
assert a is b

230

其他人已经解释了元类的工作原理以及它们如何适用于Python类型系统。这里是一个例子,说明它们可以用来做什么。在我编写的一个测试框架中,我希望跟踪类定义的顺序,以便稍后以此顺序实例化它们。我发现使用元类最容易实现这一点。

class MyMeta(type):

    counter = 0

    def __init__(cls, name, bases, dic):
        type.__init__(cls, name, bases, dic)
        cls._order = MyMeta.counter
        MyMeta.counter += 1

class MyType(object):              # Python 2
    __metaclass__ = MyMeta

class MyType(metaclass=MyMeta):    # Python 3
    pass

任何MyType的子类都会获得一个名为_order的类属性,该属性记录了定义这些类的顺序。


谢谢你的示例。为什么你觉得这比从MyBase继承更容易,而MyBase的__init__(self)type(self)._order = MyBase.counter; MyBase.counter += 1 - Michael Gundlach
6
我希望对类本身进行编号,而不是它们的实例。 - kindall
好的,谢谢。我的代码会在每次实例化时重置MyType的属性,并且如果从未创建MyType的实例,则永远不会设置该属性。糟糕了。(类属性也可以工作,但与元类不同,它没有明显的存储计数器的位置。) - Michael Gundlach
1
这是一个非常有趣的例子,其中最重要的原因是可以真正看到为什么需要使用元类来解决特定困难。另一方面,我很难相信任何人真的需要按照类定义的顺序实例化对象:我想我们只能相信你的话 :)。 - mike rodent
3
这是一个文档测试框架,其中类是特定文件的声明性描述,用于测试和运行等。该框架会生成漂亮格式的报告,按产品、文档和测试分组列出结果。如果按可预测的顺序运行测试,则报告更有用。 :-) - kindall

200

元类的一个用途是自动向实例添加新属性和方法。

例如,如果您查看Django模型(Django models),它们的定义看起来有点令人困惑。看起来好像您只能定义类属性:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

然而,在运行时,Person对象被填充了各种有用的方法。请参阅源代码,以了解一些神奇的元类技巧。


12
使用元类不是为实例添加新的属性和方法,而是为类添加新的属性和方法。据我理解,元类会改变类本身,从而通过修改后的类可以以不同的方式构建实例。对于试图理解元类本质的人来说可能会有些误导性。在实例上使用有用的方法可以通过普通继承来实现。然而,引用Django代码作为示例是很好的。 - trixn

162

我认为ONLamp关于元类编程的介绍写得很好,尽管已经过了几年,但对这个主题的介绍非常好。

http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html (存档于https://web.archive.org/web/20080206005253/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html)

简而言之:类是实例创建的蓝图,元类是类创建的蓝图。可以很容易地看出,在Python中,类也需要成为一等对象才能实现这种行为。

我从未亲自编写过,但我认为元类最美妙的用途之一可以在Django框架中看到。模型类使用元类方法来启用声明性编写新模型或表单类的方式。当元类正在创建类时,所有成员都有可能自定义类本身。

还有一件事要说:如果你不知道什么是元类,那么你几乎不需要它们,这个概率达到了99%。


150

元类是什么?你如何使用它们?

简而言之:元类像类一样实例化并定义类的行为,就像类实例化并定义实例的行为。

伪代码:

>>> Class(...)
instance

上面的内容应该很熟悉。那么,Class 是从哪里来的呢?它是元类(也是伪代码)的一个实例:
>>> Metaclass(...)
Class

在实际的代码中,我们可以传递默认元类type,以及实例化一个类所需的一切,然后获得一个类:

>>> type('Foo', (object,), {}) # requires a name, bases, and a namespace
<class '__main__.Foo'>

换句话说

  • A class is to an instance as a metaclass is to a class.

    When we instantiate an object, we get an instance:

    >>> object()                          # instantiation of class
    <object object at 0x7f9069b4e0b0>     # instance
    

    Likewise, when we define a class explicitly with the default metaclass, type, we instantiate it:

    >>> type('Object', (object,), {})     # instantiation of metaclass
    <class '__main__.Object'>             # instance
    
  • Put another way, a class is an instance of a metaclass:

    >>> isinstance(object, type)
    True
    
  • Put a third way, a metaclass is a class's class.

    >>> type(object) == type
    True
    >>> object.__class__
    <class 'type'>
    

当你编写一个类定义并在Python中执行时,它使用元类来实例化类对象(这个类对象将被用于实例化该类的实例)。

正如我们可以使用类定义来改变自定义对象实例的行为一样,我们可以使用元类类定义来改变类对象的行为。

它们可以用于什么?根据docs

元类的潜在用途是无限的。一些已经探索过的想法包括日志记录、接口检查、自动委托、自动属性创建、代理、框架和自动资源锁定/同步。

尽管如此,通常鼓励用户避免使用元类,除非绝对必要。

每次创建类时都会使用元类:

例如,当您编写类定义时,就像这样:

class Foo(object): 
    'demo'

您实例化一个类对象。

>>> Foo
<class '__main__.Foo'>
>>> isinstance(Foo, type), isinstance(Foo, object)
(True, True)

这与使用适当的参数功能性地调用type函数并将结果分配给该名称的变量相同:
name = 'Foo'
bases = (object,)
namespace = {'__doc__': 'demo'}
Foo = type(name, bases, namespace)

请注意,有些内容会自动添加到__dict__中,即命名空间:

>>> Foo.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'Foo' objects>, 
'__module__': '__main__', '__weakref__': <attribute '__weakref__' 
of 'Foo' objects>, '__doc__': 'demo'})

我们创建的对象的元类在两种情况下都是`type`。
(关于类`__dict__`的内容的一个侧注:`__module__`存在是因为类必须知道它们定义在哪里,而`__dict__`和`__weakref__`存在是因为我们没有定义`__slots__`。如果我们定义了__slots__,我们可以通过排除它们来禁止`__dict__`和`__weakref__`,从而节省实例中的一些空间。例如:)
>>> Baz = type('Bar', (object,), {'__doc__': 'demo', '__slots__': ()})
>>> Baz.__dict__
mappingproxy({'__doc__': 'demo', '__slots__': (), '__module__': '__main__'})

(但我跑题了。)

我们可以像定义其他类一样扩展type

这里是类的默认__repr__

>>> Foo
<class '__main__.Foo'>

在编写Python对象时,默认情况下最有价值的事情之一是为其提供一个良好的__repr__。当我们调用help(repr)时,我们会发现有一个很好的测试__repr__的方法,也需要测试相等性:obj == eval(repr(obj))。以下是我们类型类的类实例的__repr____eq__的简单实现,它们可以为我们提供演示,可能会改进类的默认__repr__

class Type(type):
    def __repr__(cls):
        """
        >>> Baz
        Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
        >>> eval(repr(Baz))
        Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
        """
        metaname = type(cls).__name__
        name = cls.__name__
        parents = ', '.join(b.__name__ for b in cls.__bases__)
        if parents:
            parents += ','
        namespace = ', '.join(': '.join(
          (repr(k), repr(v) if not isinstance(v, type) else v.__name__))
               for k, v in cls.__dict__.items())
        return '{0}(\'{1}\', ({2}), {{{3}}})'.format(metaname, name, parents, namespace)
    def __eq__(cls, other):
        """
        >>> Baz == eval(repr(Baz))
        True            
        """
        return (cls.__name__, cls.__bases__, cls.__dict__) == (
                other.__name__, other.__bases__, other.__dict__)

现在,当我们使用这个元类创建一个对象时,命令行上打印的__repr__看起来比默认情况下要好得多:

>>> class Bar(object): pass
>>> Baz = Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
>>> Baz
Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})

使用一个良好定义的 __repr__ 方法,我们能够更强大地调试代码。但是,eval(repr(Class)) 的进一步检查可能不太可能(因为从默认的 __repr__ 中评估函数会相当困难)。

预期的用法:__prepare__ 命名空间

例如,如果我们想知道一个类的方法创建顺序,我们可以将有序字典作为类的命名空间。我们可以使用 __prepare__ 实现这一点,该方法 在 Python 3 中返回类的命名空间字典
from collections import OrderedDict

class OrderedType(Type):
    @classmethod
    def __prepare__(metacls, name, bases, **kwargs):
        return OrderedDict()
    def __new__(cls, name, bases, namespace, **kwargs):
        result = Type.__new__(cls, name, bases, dict(namespace))
        result.members = tuple(namespace)
        return result

使用方法:

class OrderedMethodsObject(object, metaclass=OrderedType):
    def method1(self): pass
    def method2(self): pass
    def method3(self): pass
    def method4(self): pass

现在我们有了这些方法(以及其他类属性)被创建的顺序记录:
>>> OrderedMethodsObject.members
('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4')

注意,这个例子是从文档改编而来的 - 标准库中的枚举可以实现这一点。
所以我们所做的就是通过创建一个类来实例化元类。我们也可以像处理其他类一样处理元类。它有一个方法解析顺序:
>>> inspect.getmro(OrderedType)
(<class '__main__.OrderedType'>, <class '__main__.Type'>, <class 'type'>, <class 'object'>)

它大致具有正确的repr(除非我们能找到一种表示函数的方法,否则我们将无法再进行评估):

>>> OrderedMethodsObject
OrderedType('OrderedMethodsObject', (object,), {'method1': <function OrderedMethodsObject.method1 at 0x0000000002DB01E0>, 'members': ('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4'), 'method3': <function OrderedMet
hodsObject.method3 at 0x0000000002DB02F0>, 'method2': <function OrderedMethodsObject.method2 at 0x0000000002DB0268>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'OrderedMethodsObject' objects>, '__doc__': None, '__d
ict__': <attribute '__dict__' of 'OrderedMethodsObject' objects>, 'method4': <function OrderedMethodsObject.method4 at 0x0000000002DB0378>})

111

Python 3 更新

在元类中,目前有两个关键方法:

  • __prepare__
  • __new__

__prepare__ 允许您提供一个自定义映射(例如 OrderedDict),用作创建类时的命名空间。您必须返回您选择命名空间的实例。如果您不实现 __prepare__,将使用普通的 dict

__new__ 负责实际创建/修改最终类。

一个最基本的、什么都不做的元类如下:

class Meta(type):

    def __prepare__(metaclass, cls, bases):
        return dict()

    def __new__(metacls, cls, bases, clsdict):
        return super().__new__(metacls, cls, bases, clsdict)

一个简单的例子:

假设你想对你的属性运行一些简单的验证代码——比如它必须始终是一个intstr。如果没有元类,你的类可能会像这样:

class Person:
    weight = ValidateType('weight', int)
    age = ValidateType('age', int)
    name = ValidateType('name', str)

正如您所看到的,您必须重复属性名称两次。这会导致可能出现拼写错误以及令人烦恼的错误。

一个简单的元类可以解决这个问题:

class Person(metaclass=Validator):
    weight = ValidateType(int)
    age = ValidateType(int)
    name = ValidateType(str)

这是元类的样子(不使用__prepare__,因为它不是必需的):

class Validator(type):
    def __new__(metacls, cls, bases, clsdict):
        # search clsdict looking for ValidateType descriptors
        for name, attr in clsdict.items():
            if isinstance(attr, ValidateType):
                attr.name = name
                attr.attr = '_' + name
        # create final class and return it
        return super().__new__(metacls, cls, bases, clsdict)

一个示例运行:

p = Person()
p.weight = 9
print(p.weight)
p.weight = '9'

产生:

9
Traceback (most recent call last):
  File "simple_meta.py", line 36, in <module>
    p.weight = '9'
  File "simple_meta.py", line 24, in __set__
    (self.name, self.type, value))
TypeError: weight must be of type(s) <class 'int'> (got '9')

注意:这个例子很简单,可以用类装饰器来完成,但是假设一个实际的元类会做更多的工作。

'ValidateType'类供参考:

class ValidateType:
    def __init__(self, type):
        self.name = None  # will be set by metaclass
        self.attr = None  # will be set by metaclass
        self.type = type
    def __get__(self, inst, cls):
        if inst is None:
            return self
        else:
            return inst.__dict__[self.attr]
    def __set__(self, inst, value):
        if not isinstance(value, self.type):
            raise TypeError('%s must be of type(s) %s (got %r)' %
                    (self.name, self.type, value))
        else:
            inst.__dict__[self.attr] = value

2
请注意,自 Python 3.6 起,您可以在描述符(ValidateType)中使用 __set_name__(cls, name) 来设置描述符中的名称(self.name 和在这种情况下也是 self.attr)。这是为了不必钻入元类来处理此特定常见用例而添加的(请参阅 PEP 487)。 - Lars

101

当创建类实例时,元类的__call__()方法的作用

如果你已经学习了几个月的Python编程,你可能会遇到以下代码:

# define a class
class SomeClass(object):
    # ...
    # some definition here ...
    # ...

# create an instance of it
instance = SomeClass()

# then call the object as if it's a function
result = instance('foo', 'bar')

当你在类上实现__call__()魔法方法时,后者是可能的。

class SomeClass(object):
    # ...
    # some definition here ...
    # ...

    def __call__(self, foo, bar):
        return bar + foo
__call__()方法在将一个类的实例用作可调用时被调用。但是,从之前的答案中我们可以看到,一个类本身就是一个元类的实例,因此当我们将类用作可调用(即创建其实例)时,实际上是调用其元类的__call__()方法。此时,大多数Python程序员会感到困惑,因为他们被告知在像这样创建实例instance = SomeClass()时,你在调用它的__init__()方法。一些深入挖掘过的人知道,在__init__()之前有__new__()。好吧,今天揭示了另一层真相,在__new__()之前有元类的__call__()

让我们具体从创建类的实例的角度研究方法调用链。

这是一个元类,记录实例创建之前的确切时刻以及即将返回该实例的时刻。

class Meta_1(type):
    def __call__(cls):
        print "Meta_1.__call__() before creating an instance of ", cls
        instance = super(Meta_1, cls).__call__()
        print "Meta_1.__call__() about to return instance."
        return instance

这是一个使用元类的类。
class Class_1(object):

    __metaclass__ = Meta_1

    def __new__(cls):
        print "Class_1.__new__() before creating an instance."
        instance = super(Class_1, cls).__new__(cls)
        print "Class_1.__new__() about to return instance."
        return instance

    def __init__(self):
        print "entering Class_1.__init__() for instance initialization."
        super(Class_1,self).__init__()
        print "exiting Class_1.__init__()."

现在让我们创建一个Class_1的实例

instance = Class_1()
# Meta_1.__call__() before creating an instance of <class '__main__.Class_1'>.
# Class_1.__new__() before creating an instance.
# Class_1.__new__() about to return instance.
# entering Class_1.__init__() for instance initialization.
# exiting Class_1.__init__().
# Meta_1.__call__() about to return instance.

请注意,上面的代码实际上除了记录任务外并没有做任何事情。每个方法都将实际工作委托给其父类的实现,从而保持默认行为。由于typeMeta_1的父类(type是默认父元类),并考虑输出顺序的排序序列,我们现在可以猜测type.__call__()的伪实现是什么:
class type:
    def __call__(cls, *args, **kwarg):

        # ... maybe a few things done to cls here

        # then we call __new__() on the class to create an instance
        instance = cls.__new__(cls, *args, **kwargs)

        # ... maybe a few things done to the instance here

        # then we initialize the instance with its __init__() method
        instance.__init__(*args, **kwargs)

        # ... maybe a few more things done to instance here

        # then we return it
        return instance

我们可以看到,元类的__call__()方法是首先被调用的。然后它将实例的创建委托给类的__new__()方法,并将初始化委托给实例的__init__()方法。最终它返回实例。
由此可见,元类的__call__()方法也有机会决定是否最终调用Class_1.__new__()Class_1.__init__()。在执行过程中,它实际上可以返回一个未经这些方法处理的对象。例如,考虑单例模式的这种方法:
class Meta_2(type):
    singletons = {}

    def __call__(cls, *args, **kwargs):
        if cls in Meta_2.singletons:
            # we return the only instance and skip a call to __new__()
            # and __init__()
            print ("{} singleton returning from Meta_2.__call__(), "
                   "skipping creation of new instance.".format(cls))
            return Meta_2.singletons[cls]

        # else if the singleton isn't present we proceed as usual
        print "Meta_2.__call__() before creating an instance."
        instance = super(Meta_2, cls).__call__(*args, **kwargs)
        Meta_2.singletons[cls] = instance
        print "Meta_2.__call__() returning new instance."
        return instance

class Class_2(object):

    __metaclass__ = Meta_2

    def __new__(cls, *args, **kwargs):
        print "Class_2.__new__() before creating instance."
        instance = super(Class_2, cls).__new__(cls)
        print "Class_2.__new__() returning instance."
        return instance

    def __init__(self, *args, **kwargs):
        print "entering Class_2.__init__() for initialization."
        super(Class_2, self).__init__()
        print "exiting Class_2.__init__()."

让我们观察反复尝试创建Class_2类型对象时会发生什么。

a = Class_2()
# Meta_2.__call__() before creating an instance.
# Class_2.__new__() before creating instance.
# Class_2.__new__() returning instance.
# entering Class_2.__init__() for initialization.
# exiting Class_2.__init__().
# Meta_2.__call__() returning new instance.

b = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.

c = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.

a is b is c # True

3
这是之前被点赞的“采纳答案”的很好的补充。它为中级编码人员提供了一些例子来思考。 - Rich Lysakowski PhD

77
一个元类是一种类,它告诉如何创建(某些)其他类。
这是我遇到的一个问题,使用元类作为解决方案: 我有一个非常复杂的问题,可能可以用其他方法解决,但我选择使用元类来解决它。由于复杂性,这是我编写的少数几个模块之一,在该模块中,注释的数量超过了编写的代码量。以下是代码:
#!/usr/bin/env python

# Copyright (C) 2013-2014 Craig Phillips.  All rights reserved.

# This requires some explaining.  The point of this metaclass excercise is to
# create a static abstract class that is in one way or another, dormant until
# queried.  I experimented with creating a singlton on import, but that did
# not quite behave how I wanted it to.  See now here, we are creating a class
# called GsyncOptions, that on import, will do nothing except state that its
# class creator is GsyncOptionsType.  This means, docopt doesn't parse any
# of the help document, nor does it start processing command line options.
# So importing this module becomes really efficient.  The complicated bit
# comes from requiring the GsyncOptions class to be static.  By that, I mean
# any property on it, may or may not exist, since they are not statically
# defined; so I can't simply just define the class with a whole bunch of
# properties that are @property @staticmethods.
#
# So here's how it works:
#
# Executing 'from libgsync.options import GsyncOptions' does nothing more
# than load up this module, define the Type and the Class and import them
# into the callers namespace.  Simple.
#
# Invoking 'GsyncOptions.debug' for the first time, or any other property
# causes the __metaclass__ __getattr__ method to be called, since the class
# is not instantiated as a class instance yet.  The __getattr__ method on
# the type then initialises the class (GsyncOptions) via the __initialiseClass
# method.  This is the first and only time the class will actually have its
# dictionary statically populated.  The docopt module is invoked to parse the
# usage document and generate command line options from it.  These are then
# paired with their defaults and what's in sys.argv.  After all that, we
# setup some dynamic properties that could not be defined by their name in
# the usage, before everything is then transplanted onto the actual class
# object (or static class GsyncOptions).
#
# Another piece of magic, is to allow command line options to be set in
# in their native form and be translated into argparse style properties.
#
# Finally, the GsyncListOptions class is actually where the options are
# stored.  This only acts as a mechanism for storing options as lists, to
# allow aggregation of duplicate options or options that can be specified
# multiple times.  The __getattr__ call hides this by default, returning the
# last item in a property's list.  However, if the entire list is required,
# calling the 'list()' method on the GsyncOptions class, returns a reference
# to the GsyncListOptions class, which contains all of the same properties
# but as lists and without the duplication of having them as both lists and
# static singlton values.
#
# So this actually means that GsyncOptions is actually a static proxy class...
#
# ...And all this is neatly hidden within a closure for safe keeping.
def GetGsyncOptionsType():
    class GsyncListOptions(object):
        __initialised = False

    class GsyncOptionsType(type):
        def __initialiseClass(cls):
            if GsyncListOptions._GsyncListOptions__initialised: return

            from docopt import docopt
            from libgsync.options import doc
            from libgsync import __version__

            options = docopt(
                doc.__doc__ % __version__,
                version = __version__,
                options_first = True
            )

            paths = options.pop('<path>', None)
            setattr(cls, "destination_path", paths.pop() if paths else None)
            setattr(cls, "source_paths", paths)
            setattr(cls, "options", options)

            for k, v in options.iteritems():
                setattr(cls, k, v)

            GsyncListOptions._GsyncListOptions__initialised = True

        def list(cls):
            return GsyncListOptions

        def __getattr__(cls, name):
            cls.__initialiseClass()
            return getattr(GsyncListOptions, name)[-1]

        def __setattr__(cls, name, value):
            # Substitut option names: --an-option-name for an_option_name
            import re
            name = re.sub(r'^__', "", re.sub(r'-', "_", name))
            listvalue = []

            # Ensure value is converted to a list type for GsyncListOptions
            if isinstance(value, list):
                if value:
                    listvalue = [] + value
                else:
                    listvalue = [ None ]
            else:
                listvalue = [ value ]

            type.__setattr__(GsyncListOptions, name, listvalue)

    # Cleanup this module to prevent tinkering.
    import sys
    module = sys.modules[__name__]
    del module.__dict__['GetGsyncOptionsType']

    return GsyncOptionsType

# Our singlton abstract proxy class.
class GsyncOptions(object):
    __metaclass__ = GetGsyncOptionsType()

2
Pylint说你的代码评分为-1.03/10。 - Leroy Scandal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接