Python 中的metaclasses是什么?
在 Python 中,metaclasses是什么,我们用它们做什么?
-
metaclass是类的类。类定义类的实例(即对象)的行为方式,而元类定义类的行为方式。类是metaclass的实例。
虽然在 Python 中您可以为metaclass使用任意可调用对象,但更好的方法是使其成为一个实际的类本身。
type
是 Python 中常见的元类。type
本身是一个类,它是它自己的类型。您将无法type
完全用 Python重新创建类似的东西,但 Python 会作弊。要在 Python 中创建自己的元类,您实际上只想将type
.metaclass最常用作类工厂。当您通过调用类创建对象时,Python 会通过调用元类创建一个新类(当它执行“class”语句时)。因此,结合常规
__init__
和__new__
方法,元类允许您在创建类时做“额外的事情”,例如使用某些注册表注册新类或完全用其他内容替换该类。当
class
被执行的语句,Python的首先执行的主体class
声明为代码的正常块。生成的命名空间(一个 dict)保存了类的属性。metaclass是通过查看类的基类(metaclass是继承的)、类的__metaclass__
属性(如果有)或__metaclass__
全局变量来确定的。然后使用类的名称、基类和属性调用metaclass以实例化它。然而,metaclass实际上定义了一个类的类型,而不仅仅是它的工厂,所以你可以用它们做更多的事情。例如,您可以在metaclass上定义普通方法。这些metaclass方法类似于类方法,因为它们可以在没有实例的类上调用,但它们也不像类方法,因为它们不能在类的实例上调用。
type.__subclasses__()
是type
元类方法的一个例子。您还可以定义普通的“魔法”方法,例如__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__
-
类作为对象
在理解元类之前,您需要掌握 Python 中的类。Python 对什么是类有一个非常奇特的想法,它是从 Smalltalk 语言中借来的。
在大多数语言中,类只是描述如何生成对象的代码片段。在 Python 中也是如此:
>>> class ObjectCreator(object): ... pass ... >>> my_object = ObjectCreator() >>> print(my_object) <__main__.ObjectCreator object at 0x8974f2c>
但是类比 Python 中的要多。类也是对象。
是的,对象。
只要您使用关键字
class
,Python 就会执行它并创建一个对象。指令>>> class ObjectCreator(object): ... pass ...
在内存中创建一个名为 的对象
ObjectCreator
。这个对象(类)本身能够创建对象(实例),这就是为什么它是一个类。
但是,它仍然是一个对象,因此:
- 你可以将它分配给一个变量
- 你可以复制它
- 你可以给它添加属性
- 您可以将其作为函数参数传递
例如:
>>> print(ObjectCreator) # you can print a class because it's an object <class '__main__.ObjectCreator'> >>> def echo(o): ... print(o) ... >>> echo(ObjectCreator) # you can pass a class as a parameter <class '__main__.ObjectCreator'> >>> print(hasattr(ObjectCreator, 'new_attribute')) False >>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class >>> print(hasattr(ObjectCreator, 'new_attribute')) True >>> print(ObjectCreator.new_attribute) foo >>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable >>> print(ObjectCreatorMirror.new_attribute) foo >>> print(ObjectCreatorMirror()) <__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
: 包含属性名称和值的字典
例如:
>>> 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 中,类是对象,您可以动态地动态创建类。
这就是 Python 在使用关键字
class
时所做的事情,它通过使用元类来实现。什么是元类(最后)
元类是创建类的“东西”。
您定义类是为了创建对象,对吗?
但是我们了解到 Python 类是对象。
嗯,元类是创建这些对象的原因。它们是类的类,您可以这样描述它们:
MyClass = MetaClass() my_object = MyClass()
您已经看到,它
type
可以让您执行以下操作:MyClass = type('MyClass', (), {})
这是因为函数
type
实际上是一个元类。type
是 Python 用于在幕后创建所有类的元类。现在你想知道“为什么它是用小写的,而不是用小写的
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__
any是什么__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 执行以下操作:
有
__metaclass__
属性Foo
吗?如果是,在内存中创建一个类对象(我说的是一个类对象,请留在我这里),并
Foo
使用 in 中的内容命名__metaclass__
。如果 Python 找不到
__metaclass__
,它会__metaclass__
在 MODULE 级别寻找 a ,并尝试做同样的事情(但仅限于不继承任何东西的类,基本上是旧式的类)。然后,如果它根本找不到任何
__metaclass__
,它将使用Bar
‘s(第一个父级)自己的元类(这可能是默认的type
)来创建类对象。这里要注意
__metaclass__
属性不会被继承,父类 (Bar.__class__
)的元类会被继承。如果Bar
使用的__metaclass__
是创建的属性Bar
与type()
(不是type.__new__()
),子类不会继承该行为。现在最大的问题是,你可以放入
__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__
实际上可以是任何可调用的,它不需要是一个正式的类(我知道,名称中带有 ‘class’ 的东西不需要是一个类,去图......但它很有帮助)。所以我们将从一个简单的例子开始,通过使用一个函数。
# 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
接收实例作为第一个参数的普通方法,或者类方法的定义类一样。但这不是正确的 OOP。我们
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() } return super(UpperAttrMetaclass, cls).__new__( cls, clsname, bases, uppercase_attrs)
哦,在 Python 3 中,如果您使用关键字参数执行此调用,如下所示:
class Foo(object, metaclass=MyMetaclass, kwarg1=value1): ...
它在元类中转换为 this 以使用它:
class MyMetaclass(type): def __new__(cls, clsname, bases, dct, kwargs1=default): ...
而已。真的没有更多关于元类的了。
使用元类的代码的复杂性背后的原因不是因为元类,而是因为您通常使用元类来做依赖内省、操作继承、诸如 的变量等扭曲的东西
__dict__
。确实,元类对于做黑魔法特别有用,因此也很复杂。但就其本身而言,它们很简单:
- 拦截类创建
- 修改类
- 返回修改后的类
为什么要使用元类而不是函数?
既然
__metaclass__
可以接受任何可调用对象,为什么要使用类,因为它显然更复杂?这样做有几个原因:
- 意图很明确。当你阅读时
UpperAttrMetaclass(type)
,你知道接下来会发生什么 - 您可以使用 OOP。元类可以继承元类,覆盖父方法。元类甚至可以使用元类。
- 如果您指定了元类类,则类的子类将是其元类的实例,但不是使用元类函数。
- 您可以更好地构建代码。你永远不会将元类用于像上面的例子那样琐碎的事情。它通常用于复杂的事情。能够创建多个方法并将它们组合在一个类中对于使代码更易于阅读非常有用。
- 你可以挂上
__new__
,__init__
和__call__
。这将允许您做不同的事情,即使通常您可以全部完成__new__
,但有些人使用__init__
. - 这些被称为元类,该死!一定是什么意思!
为什么要使用元类?
现在是大问题。为什么要使用一些容易出错的功能?
好吧,通常你不会:
元类是更深层次的魔法,99% 的用户都不应该担心它。如果您想知道是否需要它们,则不需要(真正需要它们的人肯定知道他们需要它们并且不需要解释原因)。
Python 大师蒂姆·彼得斯
元类的主要用例是创建 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 和使用元类,从这个 API 重新创建代码来完成幕后的真正工作,使复杂的事情看起来很简单。
最后一个字
首先,您知道类是可以创建实例的对象。
嗯,事实上,类本身就是实例。元类。
>>> class Foo(object): pass >>> id(Foo) 142630324
在 Python 中一切都是对象,它们都是类的实例或元类的实例。
除了
type
.type
实际上是它自己的元类。这不是您可以在纯 Python 中重现的东西,而是通过在实现级别上作弊来完成的。其次,元类很复杂。您可能不想将它们用于非常简单的类更改。您可以使用两种不同的技术来更改类:
- monkey patching
- class decorators
99% 的情况下您需要更改类,最好使用这些。
但是在 98% 的情况下,您根本不需要类更改。