Home > Backend Development > Python Tutorial > Introduction to metaclasses in Python

Introduction to metaclasses in Python

巴扎黑
Release: 2017-09-03 12:03:02
Original
1147 people have browsed it

Translation Note: 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. 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
Copy after login

<__main__.objectcreator object="" at="" 0x8974f2c="">

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
…
Copy after login

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 attributes to it

4) You can pass it as a function parameter

The following is an example:

>>> print ObjectCreator     
# 你可以打印一个类,因为它其实也是一个对象
>>> def echo(o):
…       print o
…
>>> echo(ObjectCreator)
            
# 你可以将类做为参数传给函数
>>> print hasattr(ObjectCreator, &#39;new_attribute&#39;)
Fasle
>>> ObjectCreator.new_attribute = &#39;foo&#39; 
#  你可以为类增加属性
>>> print hasattr(ObjectCreator, &#39;new_attribute&#39;)
True
>>> print ObjectCreator.new_attribute
foo
>>> ObjectCreatorMirror = ObjectCreator 
# 你可以将类赋值给一个变量
>>> print ObjectCreatorMirror()
<__main__.objectcreator object="" at="" 0x8997b4c="">
Copy after login

Create dynamically Classes

Because classes are 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              
# 函数返回的是类,不是类的实例>>> print MyClass()            
# 你可以通过这个类创建类实例,也就是对象
<__main__.foo object="" at="" 0x89c6d4c="">
Copy after login

But this is not dynamic enough because 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())
Copy after login

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 for backward compatibility in Python)

type works Works 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
Copy after login

Can be created manually like this:

>>> MyShinyClass = type(&#39;MyShinyClass&#39;, (), {})  
# 返回一个类对象
>>> print MyShinyClass
>>> print MyShinyClass()  
#  创建一个该类的实例
<__main__.myshinyclass object="" at="" 0x8997cec="">
Copy after login

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

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

>>> class Foo(object):
…       bar = True
Copy after login

can be translated to:

>>> Foo = type(&#39;Foo&#39;, (), {&#39;bar&#39;:True})
Copy after login

and Foo can be used like a normal class:

>>> print Foo
>>> print Foo.bar
True
>>> f = Foo()
>>> print f
<__main__.foo object="" at="" 0x8a9b84c="">
>>> print f.bar
True
Copy after login

Of course, you can inherit from this class, so the following code:

>>> class FooChild(Foo):
…       pass
Copy after login

can be written as:

>>> FooChild = type(&#39;FooChild&#39;, (Foo,),{})
>>> print FooChild
>>> print FooChild.bar   
# bar属性是由Foo继承而来
True
Copy after login

Eventually you will want to add methods to your class. Just define a function with the appropriate signature and assign it as a property.

>>> 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, &#39;echo_bar&#39;)
True
>>> my_foo = FooChild()
>>> my_foo.echo_bar()
True
Copy after login

You can see that in Python, classes are also objects, and you can create classes dynamically. This is what Python does behind the scenes when you use the keyword class, and this is achieved through metaclasses.

What exactly is a metaclass (finally to the topic)

Metaclasses are the "things" used to create classes. You create a class just to create an instance object of the class, right? But we have learned that classes in Python are also objects. Well, metaclasses are used to create these classes (objects). Metaclasses are classes of classes. You can understand it like this:

MyClass = MetaClass()
MyObject = MyClass()
Copy after login

You have seen that type allows you to do something like this:

MyClass = type(&#39;MyClass&#39;, (), {})
Copy after login

This is because function type is actually a metaclass. type is the metaclass that Python uses behind the scenes to create all classes. Now you want to know why type is all lowercase instead of Type? Well, I guess this is for consistency with str, which is the class used to create string objects, and int, which is the class used to create integer objects. Type is the class that creates the class object. You can see this by inspecting the __class__ attribute. Everything in Python—and I mean everything—is an object. This includes integers, strings, functions, and classes. They are all objects, and they are all created from a class.

>>> age = 35
>>> age.__class__
>>> name = &#39;bob&#39;
>>> name.__class__
>>> def foo(): pass
>>>foo.__class__
>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__
Copy after login

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

>>> a.__class__.__class__
>>> age.__class__.__class__
>>> foo.__class__.__class__
>>> b.__class__.__class__
Copy after login

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

__metaclass__属性

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

class Foo(object):
    __metaclass__ = something…
[…]
Copy after login

如果你这么做了,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;
Copy after login

现在让我们再做一次,这一次用一个真正的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)
Copy after login

你可能已经注意到了有个额外的参数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)
Copy after login

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

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()
Copy after login

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

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

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

结语

首先,你知道了类其实是能够创建出类实例的对象。好吧,事实上,类本身也是实例,当然,它们是元类的实例。

>>>class Foo(object): pass
>>> id(Foo)
Copy after login

Python中的一切都是对象,它们要么是类的实例,要么是元类的实例,除了type。type实际上是它自己的元类,在纯Python环境中这可不是你能够做到的,这是通过在实现层面耍一些小手段做到的。其次,元类是很复杂的。对于非常简单的类,你可能不希望通过使用元类来对类做修改。你可以通过其他两种技术来修改类:

1) Monkey patching

2)   class decorators

当你需要动态修改类时,99%的时间里你最好使用上面这两种技术。当然了,其实在99%的时间里你根本就不需要动态修改类 :D

The above is the detailed content of Introduction to metaclasses in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template