Python 中的元类是什么?

问题描述:

什么是元类?它们是用来做什么的?

解决方案1:

huntsbot.com – 高效赚钱,自由工作

作为对象的类

在了解元类之前,您需要掌握 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

>>> def echo(o):
...       print(o)
...
>>> echo(ObjectCreator) # you can pass a class as a parameter

>>> 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

>>> print(MyClass()) # you can create an object from this class
<__main__.Foo object at 0x89c6d4c>

但它不是那么动态的,因为你仍然需要自己编写整个类。

由于类是对象,因此它们必须由某些东西生成。

当您使用 class 关键字时,Python 会自动创建此对象。但与 Python 中的大多数事情一样,它为您提供了一种手动完成的方法。

还记得函数 type 吗?让您知道对象是什么类型的旧函数:

>>> print(type(1))

>>> print(type("1"))

>>> print(type(ObjectCreator))

>>> print(type(ObjectCreator()))


嗯,type 有一个完全不同的能力,它还可以动态创建类。 type 可以将类的描述作为参数,并返回一个类。

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

type 以这种方式工作:

type(name, bases, attrs)

在哪里:

名称:类的名称

bases:父类的元组(用于继承,可以为空)

attrs:包含属性名称和值的字典

例如:

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

可以通过这种方式手动创建:

>>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object
>>> print(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)

>>> 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)

>>> 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__

>>> name = 'bob'
>>> name.__class__

>>> def foo(): pass
>>> foo.__class__

>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__


现在,任何 classclass 是什么?

>>> age.__class__.__class__

>>> name.__class__.__class__

>>> foo.__class__.__class__

>>> b.__class__.__class__


因此,元类只是创建类对象的东西。

如果你愿意,你可以称它为“类工厂”。

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,它将在 MODULE 级别查找 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__ 属性,而是使用基类列表中的关键字参数。

然而,元类的行为保持 largely the same。

在 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。元类可以继承元类,覆盖父方法。元类甚至可以使用元类。

如果您指定了元类类,则类的子类将是其元类的实例,但不使用元类函数。

您可以更好地构建代码。您永远不会将元类用于像上面的示例这样微不足道的事情。它通常用于复杂的事情。能够创建多个方法并将它们分组到一个类中对于使代码更易于阅读非常有用。

您可以挂接 newinitcall。这将允许你做不同的事情,即使通常你可以在 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 中重现的东西,而是通过在实现级别上作弊来完成的。

其次,元类很复杂。您可能不想将它们用于非常简单的类更改。您可以使用两种不同的技术更改类:

猴子补丁

类装饰器

99% 的时间你需要改变班级,你最好使用这些。

但是 98% 的情况下,您根本不需要更改班级。

似乎在 Django models.Model 中它不使用 __metaclass__ 而是使用 class Model(metaclass=ModelBase): 来引用 ModelBase 类,然后该类执行上述元类魔术。好帖子!这是 Django 源代码:github.com/django/django/blob/master/django/db/models/…

<<这里注意__metaclass__属性不会被继承,父类(Bar.__class__)的元类会被继承。如果 Bar 使用了通过 type()(而不是 type.__new__())创建 Bar 的 __metaclass__ 属性,则子类将不会继承该行为。>> -- 你/有人能更深入地解释一下这段话吗?

@MaxGoodridge 那是元类的 Python 3 语法。参见 Python 3.6 Data model 与 Python 2.7 Data model

Now you wonder why the heck is it written in lowercase, and not Type? - 因为它是用 C 实现的 - 这与 defaultdict 是小写而 OrderedDict(在 python 2 中)是正常的 CamelCase 的原因相同

这是一个社区 wiki 答案(因此,那些评论更正/改进的人可能会考虑将他们的评论编辑到答案中,如果他们确定他们是正确的)。

解决方案2:

huntsbot.com – 程序员副业首选,一站式外包任务、远程工作、创意产品分享订阅平台。

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

虽然在 Python 中您可以对元类使用任意可调用对象(如 Jerub 所示),但更好的方法是使其本身成为实际类。 type 是 Python 中常用的元类。 type 本身就是一个类,它是它自己的类型。您将无法纯粹在 Python 中重新创建类似 type 的内容,但 Python 会作弊。要在 Python 中创建自己的元类,您真的只想继承 type。

元类最常用作类工厂。当您通过调用类创建对象时,Python 通过调用元类创建一个新类(当它执行“类”语句时)。结合普通的 initnew 方法,元类因此允许您在创建类时做“额外的事情”,例如使用某个注册表注册新类或完全用其他东西替换该类。

执行 class 语句时,Python 首先将 class 语句的主体作为普通代码块执行。生成的命名空间(一个字典)保存了类的属性。元类是通过查看待成为类的基类(继承了元类)、待成为类的 metaclass 属性(如果有)或 metaclass 全局变量来确定的。然后使用类的名称、基类和属性调用元类以实例化它。

然而,元类实际上定义了一个类的type,而不仅仅是它的工厂,所以你可以用它们做更多的事情。例如,您可以在元类上定义普通方法。这些元类方法类似于类方法,因为它们可以在没有实例的类上调用,但它们也不像类方法,因为它们不能在类的实例上调用。 type.subclasses() 是 type 元类上的方法示例。您还可以定义普通的“魔术”方法,例如 additergetattr,以实现或更改类的行为方式。

下面是一个点点滴滴的汇总示例:

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__

class A(type):passclass B(type,metaclass=A):passb.__class__ = b

ppperry 他显然意味着如果不将类型本身用作元类,就无法重新创建类型。可以这么说。

不应该通过 Example 类的实例调用 unregister() 吗?

请注意,Python 3 不支持 __metaclass__。在 Python 3 中使用 class MyObject(metaclass=MyType),请参阅 python.org/dev/peps/pep-3115 和下面的答案。

该文档描述了 how the metaclass is chosen。元类不是继承的,而是派生的。如果你指定一个元类,它必须是每个基类元类的子类型;否则,您将使用作为其他基类元类的子类型的基类元类。请注意,可能会找到 no 有效的元类,并且定义将失败。

解决方案3:

打造属于自己的副业,开启自由职业之旅,从huntsbot.com开始!

请注意,此答案适用于 Python 2.x,因为它是在 2008 年编写的,元类在 3.x 中略有不同。

元类是让“类”发挥作用的秘诀。新样式对象的默认元类称为“类型”。

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

元类需要 3 个参数。 ‘name’、‘bases’ 和 ‘dict’

这里是秘密开始的地方。在这个示例类定义中查找名称、基数和字典的来源。

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

让我们定义一个元类来演示“类:”如何调用它。

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 (, None, , 1)
The dict has 4 elems, the keys are ['baz', '__module__', 'foo', '__metaclass__']
TestName =  'yellow'

现在,一个真正有意义的例子,这将自动使列表中的变量“属性”设置在类上,并设置为无。

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 的子类。

这是一个更具体的示例,展示了如何将“类型”子类化以创建一个在创建类时执行操作的元类。这很棘手:

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

解决方案4:

与HuntsBot一起,探索全球自由职业机会–huntsbot.com

其他人已经解释了元类如何工作以及它们如何适应 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 继承更容易,它的 __init__(self) 是 type(self)._order = MyBase.counter; MyBase.counter += 1 ?

我希望对类本身而不是它们的实例进行编号。

对,呵呵。谢谢。我的代码会在每次实例化时重置 MyType 的属性,并且如果从未创建 MyType 的实例,则永远不会设置该属性。哎呀。 (并且类属性也可以工作,但与元类不同,它没有提供存储计数器的明显位置。)

这是一个非常有趣的例子,尤其是因为人们可以真正理解为什么需要一个元类来为特定的困难提供解决方案。 OTOH 我很难相信任何人真的需要按照定义类的顺序来实例化对象:我想我们只需要相信你的话:)。

它是一个文档测试框架,类是要测试的特定文件、要运行的测试等的声明性描述。该框架在一份格式良好的报告中报告了这些结果,该报告按产品、文档和测试分组。如果测试以可预测的顺序运行,则该报告会更有用。 :-)

解决方案5:

保持自己快人一步,享受全网独家提供的一站式外包任务、远程工作、创意产品订阅服务–huntsbot.com

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

例如,如果您查看 Django models,它们的定义看起来有点混乱。看起来好像您只定义类属性:

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

然而,在运行时,Person 对象充满了各种有用的方法。请参阅 source 了解一些惊人的元分类。

使用元类不是为类而不是实例添加新的属性和方法吗?据我了解,元类改变了类本身,因此实例可以由改变的类以不同的方式构造。对于试图了解元类性质的人来说可能有点误导。在实例上拥有有用的方法可以通过正常的继承来实现。不过,以 Django 代码为例的参考很好。

解决方案6:

huntsbot.com聚合了超过10+全球外包任务平台的外包需求,寻找外包任务与机会变的简单与高效。

我认为 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 framework 中看到。模型类使用元类方法来启用编写新模型或表单类的声明式风格。当元类创建类时,所有成员都可以自定义类本身。

创建新模型

启用此功能的元类

剩下要说的是:如果你不知道元类是什么,那么你不需要它们的概率是 99%。

huntsbot.com全球7大洲远程工作机会,探索不一样的工作方式

解决方案7:

huntsbot.com精选全球7大洲远程工作机会,涵盖各领域,帮助想要远程工作的数字游民们能更精准、更高效的找到对方。

什么是元类?你用它们做什么?

TLDR:元类实例化并定义类的行为,就像类实例化并定义实例的行为一样。

伪代码:

>>> Class(...)
instance

上面应该看起来很熟悉。那么,Class 来自哪里?它是元类的一个实例(也是伪代码):

>>> Metaclass(...)
Class

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

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


换个说法

类之于实例就像元类之于类。当我们实例化一个对象时,我们得到一个实例: >>> object() # 类的实例化 # instance 同样,当我们使用默认元类 type 显式定义一个类时,我们实例化它: >> > type(‘Object’, (object,), {}) # 元类实例化 # 实例

换句话说,类是元类的实例: >>> isinstance(object, type) True

第三种方式,元类是类的类。 >>> type(object) == type True >>> object.class

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

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

它们可以用来做什么?从 docs:

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

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

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

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

class Foo(object): 
    'demo'

您实例化一个类对象。

>>> 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__': , 
'__module__': '__main__', '__weakref__': , '__doc__': 'demo'})

在这两种情况下,我们创建的对象的 元类 都是 type。

(关于类 dict 的内容的旁注:module 存在是因为类必须知道它们的定义位置,而 dictweakref 存在是因为我们没有定义 slots - 如果define slots 我们将在实例中节省一点空间,因为我们可以通过排除 dictweakref 来禁止它们。例如:

>>> Baz = type('Bar', (object,), {'__doc__': 'demo', '__slots__': ()})
>>> Baz.__dict__
mappingproxy({'__doc__': 'demo', '__slots__': (), '__module__': '__main__'})

…但我离题了。)

我们可以像任何其他类定义一样扩展类型:

这是类的默认 repr

>>> Foo


默认情况下,我们在编写 Python 对象时可以做的最有价值的事情之一就是为其提供良好的 repr。当我们调用 help(repr) 时,我们了解到有一个很好的 repr 测试还需要一个相等性测试 - obj == eval(repr(obj))。以下对我们类型类的类实例的 repreq 的简单实现为我们提供了一个可以改进类的默认 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 执行此操作,其中 returns the namespace dict for the class if it is implemented in 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')

请注意,此示例改编自 documentation - 新的 enum in the standard library 执行此操作。

所以我们所做的是通过创建一个类来实例化一个元类。我们也可以像对待任何其他类一样对待元类。它有一个方法解析顺序:

>>> inspect.getmro(OrderedType)
(, , , )

它有大约正确的 repr(除非我们能找到一种方法来表示我们的函数,否则我们不能再评估它。):

>>> OrderedMethodsObject
OrderedType('OrderedMethodsObject', (object,), {'method1': , 'members': ('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4'), 'method3': , 'method2': , '__module__': '__main__', '__weakref__': , '__doc__': None, '__d
ict__': , 'method4': })

解决方案8:

一个优秀的自由职业者,应该有对需求敏感和精准需求捕获的能力,而huntsbot.com提供了这个机会

Python 3 更新

元类中有(此时)两个关键方法:

prepare,和

新的

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)

一个简单的例子:

假设您希望在您的属性上运行一些简单的验证代码,例如它必须始终是 int 或 str。如果没有元类,您的类将类似于:

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 
    p.weight = '9'
  File "simple_meta.py", line 24, in __set__
    (self.name, self.type, value))
TypeError: weight must be of type(s)  (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

请注意,从 python 3.6 开始,您可以在描述符 (ValidateType) 中使用 __set_name__(cls, name) 来设置描述符中的名称(self.name,在这种情况下也是 self.attr)。添加此功能是为了不必深入研究此特定常见用例的元类(请参阅 PEP 487)。

解决方案9:

HuntsBot周刊–不定时分享成功产品案例,学习他们如何成功建立自己的副业–huntsbot.com

创建类实例时元类的 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_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.

请注意,上面的代码实际上除了记录任务之外没有做任何事情。每个方法都将实际工作委托给其父级的实现,从而保持默认行为。由于 type 是 Meta_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()
#  singleton returning from Meta_2.__call__(), skipping creation of new instance.

c = Class_2()
#  singleton returning from Meta_2.__call__(), skipping creation of new instance.

a is b is c # True

这是对先前赞成的“接受的答案”的一个很好的补充。它为中级编码人员提供了示例以供参考。

解决方案10:

huntsbot.com提供全网独家一站式外包任务、远程工作、创意产品分享与订阅服务!

metaclass 是一个类,它告诉应该如何创建(一些)其他类。

在这种情况下,我将 metaclass 视为我的问题的解决方案:我遇到了一个非常复杂的问题,可能可以通过不同的方式解决,但我选择使用 metaclass 来解决它。由于复杂性,它是我编写的少数模块之一,其中模块中的注释超过了已编写的代码量。这里是…

#!/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('', 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()

pylint 说你的代码被评为 -1.03/10。

解决方案11:

huntsbot.com精选全球7大洲远程工作机会,涵盖各领域,帮助想要远程工作的数字游民们能更精准、更高效的找到对方。

tl;dr 版本

type(obj) 函数为您获取对象的类型。

类的 type() 是它的元类。

要使用元类:

class Foo(object):
    __metaclass__ = MyMetaClass

type 是它自己的元类。类的类是元类——类的主体是传递给用于构造类的元类的参数。

Here 您可以阅读有关如何使用元类来自定义类构造的信息。

原文链接:https://www.huntsbot.com/qa/2VQ4/what-are-metaclasses-in-python?lang=zh_CN

HuntsBot周刊–不定时分享成功产品案例,学习他们如何成功建立自己的副业–huntsbot.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值