Home  >  Article  >  Backend Development  >  Deep understanding of metaclasses in Python

Deep understanding of metaclasses in Python

高洛峰
高洛峰Original
2016-10-17 17:41:391021browse

Annotation: This is a very popular post on Stack overflow. The questioner claimed to have mastered various concepts in Python OOP programming, but always found metaclasses difficult to understand. He knows that this must be related to introspection, but he still doesn't quite understand it. He hopes that everyone can give some practical examples and code snippets to help understand, and under what circumstances metaprogramming is needed. So e-satis gave a god-like reply, which received 985 approval points. Some people even commented that this reply should be added to Python’s official documentation. The e-satis student’s reputation points in Stack Overflow are as high as 64,271 points. The following is this wonderful reply (tip: very long)

Classes are also objects

Before understanding metaclasses, you need to master classes in Python first. The concept of classes in Python is borrowed from Smalltalk, which seems a bit strange. In most programming languages, a class is a set of code segments that describe how to create an object. This still holds true in Python:

>>> class ObjectCreator(object):
…       pass
…
>>> my_object = ObjectCreator()
>>> print my_object

<__main__.objectcreator object at>

However, classes in Python are much more than that. A class is also an object. Yes, that's right, that's the object. As long as you use the keyword class, the Python interpreter will create an object during execution. The following code snippet:

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

will create an object in memory, named ObjectCreator. This object (class) itself has the ability to create objects (class instances), and that's why it is a class. However, its essence is still an object, so you can do the following operations on it:

1) You can assign it to a variable

2) You can copy it

3) You can add to it Property

4) You can pass it as a function parameter

Here is an example:

>>> print ObjectCreator

# You can print a class because it is actually an object

>>> def echo(o):
…       print o
…
>>> echo(ObjectCreator)

将 可以# You can pass the class as a parameter to the function


>>> PRINT HASATTR (ObjectCreator, 'New_attribute')

>>> objectCreator.new_attribute = 'FOO'

# You can add attributes to the class

>>> print hasattr(ObjectCreator, 'new_attribute')

True

>>> print ObjectCreator.new_attribute

foo

>>> ObjectCreatorMirror = ObjectCreator

# You can Assign a class to a variable

>>> print ObjectCreatorMirror()

<__main__.objectcreator object at>

Create classes dynamically

Because classes are also objects, you can create them dynamically at runtime, just like any other object. First, you can create a class in a function using the class keyword.

>>> def choose_class(name):
…       if name == &#39;foo&#39;:
…           class Foo(object):
…               pass
…           return Foo     
# 返回的是类,不是类的实例
…       else:
…           class Bar(object):
…               pass
…           return Bar
…
>>> MyClass = choose_class(&#39;foo&#39;)
>>> print MyClass              
# 函数返回的是类,不是类的实例
<class &#39;__main__&#39;.Foo>
>>> print MyClass()            
# 你可以通过这个类创建类实例,也就是对象
   
<__main__.Foo object at 0x89c6d4c>

But this is not dynamic enough as you still need to code the entire class yourself. Since classes are also objects, they must be generated from something. The Python interpreter automatically creates this object when you use the class keyword. But like most things in Python, Python still provides you with manual methods. Remember the built-in function type? This old but powerful function lets you know what type an object is, like this:

>>> print type(1)

>>> print type("1")

>>> print type(ObjectCreator)

>>> print type(ObjectCreator())

Here, type has a completely different ability, it can also create classes dynamically. type can accept a class description as a parameter and return a class. (I know, it's silly to have two completely different uses of the same function depending on the parameters passed in, but this is in Python for backwards compatibility)

type can work like this:

type (class name, tuple of parent class (can be empty for inheritance), dictionary containing attributes (name and value))

For example, the following code:

>>> class MyShinyClass(object):
…       pass

can be manually like Create like this:

>>> MyShinyClass = type('MyShinyClass', (), {})

# Return a class object

>>> print MyShinyClass

>>> print MyShinyClass()

# Create an instance of this class

You will find that we use "MyShinyClass" as the class name, and it can also be used as a variable as a reference to the class. Classes and variables are different, there's no reason to make things complicated here. <__main__.myshinyclass object at>

type accepts a dictionary to define properties for the class, so

>>> class Foo(object):
…       bar = True

can be translated as:

>>> Foo = type('Foo', (), {'bar':True})

And you can use Foo as an ordinary class:

>>> print Foo

>>> print Foo.bar

True

>>> f = Foo()

>>> print f

<__main__.foo object at>

>>> print f.bar

True

当然,你可以向这个类继承,所以,如下的代码:

>>> class FooChild(Foo):

…       pass

就可以写成:

>>> FooChild = type('FooChild', (Foo,),{})

>>> print FooChild

>>> print FooChild.bar   

# bar属性是由Foo继承而来

True

最终你会希望为你的类增加方法。只需要定义一个有着恰当签名的函数并将其作为属性赋值就可以了。

>>> def echo_bar(self):
…       print self.bar
…
>>> FooChild = type(&#39;FooChild&#39;, (Foo,), {&#39;echo_bar&#39;: echo_bar})
>>> hasattr(Foo, &#39;echo_bar&#39;)

   

False

>>> hasattr(FooChild, 'echo_bar')

True

>>> my_foo = FooChild()

>>> my_foo.echo_bar()

True

你可以看到,在Python中,类也是对象,你可以动态的创建类。这就是当你使用关键字class时Python在幕后做的事情,而这就是通过元类来实现的。

 

到底什么是元类(终于到主题了)

元类就是用来创建类的“东西”。你创建类就是为了创建类的实例对象,不是吗?但是我们已经学习到了Python中的类也是对象。好吧,元类就是用来创建这些类(对象)的,元类就是类的类,你可以这样理解 为:

MyClass = MetaClass()

MyObject = MyClass()

你已经看到了type可以让你像这样做:

MyClass = type('MyClass', (), {})

这是因为函数type实际上是一个元类。type就是Python在背后用来创建所有类的元类。现在你想知道那为什么type会全部采用小写形式而不是Type呢?好吧,我猜这是为了和str保持一致性,str是用来创建字符串对象的类,而int是用来创建整数对象的类。type就是创建类对象的类。你可以通过检查__class__属性来看到这一点。Python中所有的东西,注意,我是指所有的东西——都是对象。这包括整数、字符串、函数以及类。它们全部都是对象,而且它们都是从一个类创建而来。

>>> age = 35

>>> age.__class__

>>> name = 'bob'

>>> name.__class__

>>> def foo(): pass

>>>foo.__class__

>>> class Bar(object): pass

>>> b = Bar()

>>> b.__class__

现在,对于任何一个__class__的__class__属性又是什么呢?

>>> a.__class__.__class__

>>> age.__class__.__class__

>>> foo.__class__.__class__

>>> b.__class__.__class__

因此,元类就是创建类这种对象的东西。如果你喜欢的话,可以把元类称为“类工厂”(不要和工厂类搞混了:D) type就是Python的内建元类,当然了,你也可以创建自己的元类。

 

__metaclass__属性

你可以在写一个类的时候为其添加__metaclass__属性。

class Foo(object):

    __metaclass__ = something…

[…]

如果你这么做了,Python就会用元类来创建类Foo。小心点,这里面有些技巧。你首先写下class Foo(object),但是类对象Foo还没有在内存中创建。Python会在类的定义中寻找__metaclass__属性,如果找到了,Python就会用它来创建类Foo,如果没有找到,就会用内建的type来创建这个类。把下面这段话反复读几次。当你写如下代码时 :

class Foo(Bar):

    pass

Python做了如下的操作:

Foo中有__metaclass__这个属性吗?如果是,Python会在内存中通过__metaclass__创建一个名字为Foo的类对象(我说的是类对象,请紧跟我的思路)。如果Python没有找到__metaclass__,它会继续在Bar(父类)中寻找__metaclass__属性,并尝试做和前面同样的操作。如果Python在任何父类中都找不到__metaclass__,它就会在模块层次中去寻找__metaclass__,并尝试做同样的操作。如果还是找不到__metaclass__,Python就会用内置的type来创建这个类对象。

现在的问题就是,你可以在__metaclass__中放置些什么代码呢?答案就是:可以创建一个类的东西。那么什么可以用来创建一个类呢?type,或者任何使用到type或者子类化type的东东都可以。

 

自定义元类

元类的主要目的就是为了当创建类时能够自动地改变类。通常,你会为API做这样的事情,你希望可以创建符合当前上下文的类。假想一个很傻的例子,你决定在你的模块里所有的类的属性都应该是大写形式。有好几种方法可以办到,但其中一种就是通过在模块级别设定__metaclass__。采用这种方法,这个模块中的所有类都会通过这个元类来创建,我们只需要告诉元类把所有的属性都改成大写形式就万事大吉了。

幸运的是,__metaclass__实际上可以被任意调用,它并不需要是一个正式的类(我知道,某些名字里带有‘class’的东西并不需要是一个class,画画图理解下,这很有帮助)。所以,我们这里就先以一个简单的函数作为例子开始。

# 元类会自动将你通常传给‘type’的参数作为自己的参数传入

def upper_attr(future_class_name, future_class_parents, future_class_attr):
     
&#39;&#39;&#39;返回一个类对象,将属性都转为大写形式&#39;&#39;&#39;
     
#  选择所有不以&#39;__&#39;开头的属性
    attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith(&#39;__&#39;))
     
# 将它们转为大写形式
    uppercase_attr = dict((name.upper(), value) for name, value in attrs)
  
     
# 通过&#39;type&#39;来做类对象的创建
    return type(future_class_name, future_class_parents, uppercase_attr)
  
__metaclass__ = upper_attr  
#  这会作用到这个模块中的所有类
  
class Foo(object):
     
# 我们也可以只在这里定义__metaclass__,这样就只会作用于这个类中
    bar = &#39;bip&#39;
print hasattr(Foo, &#39;bar&#39;)
# 输出: False
print hasattr(Foo, &#39;BAR&#39;)
# 输出:True
  
f = Foo()
print f.BAR
# 输出:&#39;bip&#39;

   

现在让我们再做一次,这一次用一个真正的class来当做元类。

# 请记住,&#39;type&#39;实际上是一个类,就像&#39;str&#39;和&#39;int&#39;一样
# 所以,你可以从type继承
class UpperAttrMetaClass(type):
     
# __new__ 是在__init__之前被调用的特殊方法
     
# __new__是用来创建对象并返回之的方法
     
# 而__init__只是用来将传入的参数初始化给对象
     
# 你很少用到__new__,除非你希望能够控制对象的创建
     
# 这里,创建的对象是类,我们希望能够自定义它,所以我们这里改写__new__
     
# 如果你希望的话,你也可以在__init__中做些事情
     
# 还有一些高级的用法会涉及到改写__call__特殊方法,但是我们这里不用
    def __new__(upperattr_metaclass, future_class_name, future_class_parents, future_class_attr):
        attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith(&#39;__&#39;))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)
        return type(future_class_name, future_class_parents, uppercase_attr)
但是,这种方式其实不是OOP。我们直接调用了type,而且我们没有改写父类的__new__方法。现在让我们这样去处理:
class UpperAttrMetaclass(type):
    def __new__(upperattr_metaclass, future_class_name, future_class_parents, future_class_attr):
        attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith(&#39;__&#39;))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)

  

         

# 复用type.__new__方法

         

# 这就是基本的OOP编程,没什么魔法

        return type.__new__(upperattr_metaclass, future_class_name, future_class_parents, uppercase_attr)

   

你可能已经注意到了有个额外的参数upperattr_metaclass,这并没有什么特别的。类方法的第一个参数总是表示当前的实例,就像在普通的类方法中的self参数一样。当然了,为了清晰起见,这里的名字我起的比较长。但是就像self一样,所有的参数都有它们的传统名称。因此,在真实的产品代码中一个元类应该是像这样的:

class UpperAttrMetaclass(type):
    def __new__(cls, name, bases, dct):
        attrs = ((name, value) for name, value in dct.items() if not name.startswith(&#39;__&#39;)
        uppercase_attr  = dict((name.upper(), value) for name, value in attrs)
        return type.__new__(cls, name, bases, uppercase_attr)
如果使用super方法的话,我们还可以使它变得更清晰一些,这会缓解继承(是的,你可以拥有元类,从元类继承,从type继承)
class UpperAttrMetaclass(type):
    def __new__(cls, name, bases, dct):
        attrs = ((name, value) for name, value in dct.items() if not name.startswith(&#39;__&#39;))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)
        return super(UpperAttrMetaclass, cls).__new__(cls, name, bases, uppercase_attr)

   

就是这样,除此之外,关于元类真的没有别的可说的了。使用到元类的代码比较复杂,这背后的原因倒并不是因为元类本身,而是因为你通常会使用元类去做一些晦涩的事情,依赖于自省,控制继承等等。确实,用元类来搞些“黑暗魔法”是特别有用的,因而会搞出些复杂的东西来。但就元类本身而言,它们其实是很简单的:

1)   拦截类的创建

2)   修改类

3)   返回修改之后的类

 

为什么要用metaclass类而不是函数?

由于__metaclass__可以接受任何可调用的对象,那为何还要使用类呢,因为很显然使用类会更加复杂啊?这里有好几个原因:

1)  意图会更加清晰。当你读到UpperAttrMetaclass(type)时,你知道接下来要发生什么。

2) 你可以使用OOP编程。元类可以从元类中继承而来,改写父类的方法。元类甚至还可以使用元类。

3)  你可以把代码组织的更好。当你使用元类的时候肯定不会是像我上面举的这种简单场景,通常都是针对比较复杂的问题。将多个方法归总到一个类中会很有帮助,也会使得代码更容易阅读。

4) 你可以使用__new__, __init__以及__call__这样的特殊方法。它们能帮你处理不同的任务。就算通常你可以把所有的东西都在__new__里处理掉,有些人还是觉得用__init__更舒服些。

5) 哇哦,这东西的名字是metaclass,肯定非善类,我要小心!

 

究竟为什么要使用元类?

现在回到我们的大主题上来,究竟是为什么你会去使用这样一种容易出错且晦涩的特性?好吧,一般来说,你根本就用不上它:

“元类就是深度的魔法,99%的用户应该根本不必为此操心。如果你想搞清楚究竟是否需要用到元类,那么你就不需要它。那些实际用到元类的人都非常清楚地知道他们需要做什么,而且根本不需要解释为什么要用元类。”  —— Python界的领袖 Tim Peters

元类的主要用途是创建API。一个典型的例子是Django ORM。它允许你像这样定义:

class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

   

但是如果你像这样做的话:


 
guy  = Person(name=&#39;bob&#39;, age=&#39;35&#39;)print guy.age


   

这并不会返回一个IntegerField对象,而是会返回一个int,甚至可以直接从数据库中取出数据。这是有可能的,因为models.Model定义了__metaclass__, 并且使用了一些魔法能够将你刚刚定义的简单的Person类转变成对数据库的一个复杂hook。Django框架将这些看起来很复杂的东西通过暴露出一个简单的使用元类的API将其化简,通过这个API重新创建代码,在背后完成真正的工作。

 

结语

First of all, you know that a class is actually an object that can create class instances. Well, in fact, classes themselves are instances, and of course, they are instances of metaclasses.

>>>class Foo(object): pass

>>> id(Foo)

Everything in Python is an object, they are either instances of a class or a metaclass, except type. type is actually its own metaclass. This is not something you can do in a pure Python environment. This is done by playing some tricks at the implementation level. Second, metaclasses are complex. For very simple classes, you may not want to modify the class by using metaclasses. You can modify classes through two other techniques:

1) Monkey patching

2) class decorators

When you need to dynamically modify a class, 99% of the time you are better off using the above two techniques. Of course, in fact, 99% of the time you don’t need to dynamically modify the class at all :D


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn