什么是元类以及我们用它们做什么?

有帮助吗?

解决方案

元类是类的类。类定义了该类的实例(即对象)的行为而元类定义类的行为方式。类是元类的实例。

在 Python 中,您可以对元类使用任意可调用对象(例如 杰鲁布 显示),更好的方法是使其成为一个实际的类本身。 type 是Python中常见的元类。 type 本身就是一个类,并且它有自己的类型。你将无法重新创建类似的东西 type 纯粹用Python编写,但Python有一点作弊。要在 Python 中创建自己的元类,您实际上只想子类化 type.

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

当。。。的时候 class 执行语句时,Python首先执行语句体 class 语句作为普通代码块。生成的命名空间(字典)包含待生成类的属性。元类是通过查看要成为的类的基类(元类是继承的)来确定的, __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 of the class,
     tuple of the parent class (for inheritance, can be empty),
     dictionary containing attributes names and values)

例如。:

>>> 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用来创建幕后所有类的Metaclass。

现在你想知道为什么它是用小写写的,而不是 Type?

嗯,我想这是一个一致性问题 str, ,创建字符串对象的类,以及 int 创建整数对象的类。 type 只是创建类对象的类。

通过检查您会发现 __class__ 属性。

一切,我的意思是一切,都是 Python 中的对象。其中包括INT,字符串,功能和类。它们都是对象。所有这些都是从班级创建的:

>>> 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 执行以下操作:

有没有 __metaclass__ 属性在 Foo?

如果是,则在内存中创建一个类对象(我说的是类对象,请留下来),其名称为 Foo 通过使用其中的内容 __metaclass__.

如果Python找不到 __metaclass__, ,它将寻找一个 __metaclass__ 在 MODULE 级别,并尝试执行相同的操作(但仅限于不继承任何内容的类,基本上是旧式类)。

然后如果找不到任何 __metaclass__ 无论如何,它将使用 Bar的(第一个父级)自己的元类(可能是默认的 type) 创建类对象。

这里要小心的是 __metaclass__ 属性不会被继承,父类的元类(Bar.__class__) 将。如果 Bar 用过一个 __metaclass__ 创建的属性 Bartype() (并不是 type.__new__()),子类不会继承该行为。

现在最大的问题是,你可以放入什么 __metaclass__ ?

答案是:可以创建类的东西。

什么可以创建一个类? type, ,或任何子类或使用它的东西。

Python 3 中的元类

设置元类的语法在 Python 3 中已更改:

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

IE。这 __metaclass__ 不再使用属性,取而代之的是基类列表中的关键字参数。

然而,元类的行为仍然存在 大致相同.

python 3 中元类添加的一件事是,您还可以将属性作为关键字参数传递到元类中,如下所示:

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

阅读下面的部分了解 python 如何处理这个问题。

自定义元类

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

通常,您要为API执行此操作,在其中您要创建与当前上下文相匹配的类。

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

这样,将使用此Metaclass创建此模块的所有类,我们只需要告诉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_attr):
    """
      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_attr = {}
    for name, val in future_class_attr.items():
        if not name.startswith('__'):
            uppercase_attr[name.upper()] = val
        else:
            uppercase_attr[name] = val

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

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

print(hasattr(Foo, 'bar'))
# Out: False
print(hasattr(Foo, 'BAR'))
# Out: True

f = Foo()
print(f.BAR)
# Out: '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_attr):

        uppercase_attr = {}
        for name, val in future_class_attr.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

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

        uppercase_attr = {}
        for name, val in future_class_attr.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        # reuse the type.__new__ method
        # this is basic OOP, nothing magic in there
        return type.__new__(upperattr_metaclass, future_class_name,
                            future_class_parents, uppercase_attr)

您可能已经注意到额外的参数 upperattr_metaclass. 。没有什么特别的: __new__ 始终接收其定义的类作为第一个参数。就像你一样 self 对于接收实例作为第一个参数的普通方法,或类方法的定义类。

当然,我在这里使用的名字为了清楚起见,但就像 self, ,所有参数都有约定的名称。因此,真正的生产元素看起来像这样:

class UpperAttrMetaclass(type):

    def __new__(cls, clsname, bases, dct):

        uppercase_attr = {}
        for name, val in dct.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        return type.__new__(cls, clsname, bases, uppercase_attr)

我们可以通过使用使其更加干净 super, ,这将简化继承(因为是的,您可以拥有元类,从元类继承,从类型继承):

class UpperAttrMetaclass(type):

    def __new__(cls, clsname, bases, dct):

        uppercase_attr = {}
        for name, val in dct.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        return super(UpperAttrMetaclass, cls).__new__(cls, clsname, bases, uppercase_attr)

哦,在 python 3 中,如果您使用关键字参数进行此调用,如下所示:

class Foo(object, metaclass=Thing, kwarg1=value1):
    ...

它在元类中转换为以下内容以使用它:

class Thing(type):
    def __new__(cls, clsname, bases, dct, kwargs1=default):
        ...

就是这样。关于元类确实没有更多的内容了。

使用元素的代码复杂性背后的原因不是元素,而是因为您通常使用元素来做依靠内省,操纵遗传的扭曲的事情,例如 __dict__, , ETC。

确实,元类对于做黑魔法,因此特别有用。但它们本身很简单:

  • 拦截类创建
  • 修改类
  • 返回修改后的类

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

自从 __metaclass__ 可以接受任何可召唤的人,为什么要使用班级,因为它显然更复杂?

这样做有几个原因:

  • 意图很明确。当你阅读时 UpperAttrMetaclass(type), ,你知道会遵循什么
  • 您可以使用面向对象编程。元类可以继承元类,重写父类方法。元类甚至可以使用元类。
  • 如果您指定了元类类,但没有使用元类函数,则类的子类将是其元类的实例。
  • 您可以更好地构建代码。您永远不会使用元类像上面的示例那样微不足道的东西。通常是为了一些复杂的事情。具有制作多种方法并将其分组的能力对于使代码易于阅读非常有用。
  • 你可以挂上 __new__, __init____call__. 。这将使您能够做不同的事情。即使通常你可以在 __new__,有些人使用更舒服 __init__.
  • 这些被称为元类,该死!它一定意味着什么!

为什么要使用元类?

现在是大问题。为什么要使用一些晦涩的容易出错的功能?

好吧,通常你不会:

元类是99%的用户不必担心的更深层次的魔力。如果您想知道是否需要它们,就不需要(实际上需要他们的人确定要知道他们需要它们,并且不需要解释原因)。

Python 大师蒂姆·彼得斯

元类的主要用例是创建 API。一个典型的例子是 Django ORM。

它允许您定义如下内容:

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

但如果你这样做:

guy = Person(name='bob', age='35')
print(guy.age)

它不会返回 IntegerField 目的。它将返回一个 int, ,甚至可以直接从数据库中获取。

这是可能的,因为 models.Model 定义 __metaclass__ 它使用了一些魔术会转动 Person 您只是用简单的语句定义为数据库字段的复杂钩子。

Django通过公开一个简单的API并使用元类,从该API重新创建代码来完成幕后的真实工作,从而使复杂的事物看起来很简单。

最后一个字

首先,您知道类是可以创建实例的对象。

事实上,类本身就是实例。元类。

>>> class Foo(object): pass
>>> id(Foo)
142630324

一切都是Python中的一个对象,它们都是类的实例或元类实例。

除了 type.

type 实际上是它自己的元类。这不是您可以在Pure Python中复制的东西,并且是通过在实现级别上作弊来完成的。

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

99% 的时候你需要类改变,你最好使用这些。

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

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

元类是让“类”发挥作用的秘密武器。新样式对象的默认元类称为“type”。

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

元类需要 3 个参数。'姓名', '基地' 和 '字典'

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

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 (<type 'object'>, None, <type 'int'>, 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

请注意,“Initalized”通过元类获得的神奇行为 init_attributes 不传递给 Initalized 的子类。

这是一个更具体的示例,展示了如何对“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

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

例如,如果你看 姜戈模型, ,他们的定义看起来有点混乱。看起来好像您只定义了类属性:

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

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

其他人解释了元类如何工作以及它们如何适应 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 它记录了类的定义顺序。

我认为 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%。

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

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

伪代码:

>>> Class(...)
instance

上面的内容应该看起来很熟悉。嗯,哪里有 Class 来自?它是元类的实例(也是伪代码):

>>> Metaclass(...)
Class

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

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

换种说法

  • 类对于实例就像元类对于类一样。

    当我们实例化一个对象时,我们得到一个实例:

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

    同样,当我们使用默认元类显式定义一个类时, type, ,我们实例化它:

    >>> type('Object', (object,), {})     # instantiation of metaclass
    <class '__main__.Object'>             # instance
    
  • 换句话说,类是元类的实例:

    >>> isinstance(object, type)
    True
    
  • 换句话说,元类是类的类。

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

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

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

它们可以用来做什么?来自 文档:

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

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

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

例如,当您编写类定义时,如下所示:

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

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)

一个简单的例子:

假设您希望在您的属性上运行一些简单的验证代码 - 就像它必须始终是 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 <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

元类的作用' __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

元类是一个告诉(某些)其他类应该如何创建的类。

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

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

type 实际上是一个 metaclass -- 一个类创建另一个类。最多 metaclass 是的子类 type. 。这 metaclass 收到 new class 作为其第一个参数,并提供对类对象的访问,详细信息如下:

>>> class MetaClass(type):
...     def __init__(cls, name, bases, attrs):
...         print ('class name: %s' %name )
...         print ('Defining class %s' %cls)
...         print('Bases %s: ' %bases)
...         print('Attributes')
...         for (name, value) in attrs.items():
...             print ('%s :%r' %(name, value))
... 

>>> class NewClass(object, metaclass=MetaClass):
...    get_choch='dairy'
... 
class name: NewClass
Bases <class 'object'>: 
Defining class <class 'NewClass'>
get_choch :'dairy'
__module__ :'builtins'
__qualname__ :'NewClass'

Note:

请注意,该类并非在任何时候都被实例化;创建类的简单行为触发了 metaclass.

tl;dr 版本

type(obj) 函数可以获取对象的类型。

type() 一个类的就是它的 元类.

使用元类:

class Foo(object):
    __metaclass__ = MyMetaClass

Python 类本身就是其元类的对象(如实例)。

默认元类,当您将类确定为:

class foo:
    ...

元类用于将某些规则应用于整个类集。例如,假设您正在构建一个 ORM 来访问数据库,并且您希望每个表中的记录属于映射到该表的类(基于字段、业务规则等),可能会使用元类例如,连接池逻辑,由所有表中的所有记录类共享。另一个用途是支持外键的逻辑,这涉及多类记录。

当您定义元类时,您可以对类型进行子类化,并且可以重写以下魔术方法来插入您的逻辑。

class somemeta(type):
    __new__(mcs, name, bases, clsdict):
      """
  mcs: is the base metaclass, in this case type.
  name: name of the new class, as provided by the user.
  bases: tuple of base classes 
  clsdict: a dictionary containing all methods and attributes defined on class

  you must return a class object by invoking the __new__ constructor on the base metaclass. 
 ie: 
    return type.__call__(mcs, name, bases, clsdict).

  in the following case:

  class foo(baseclass):
        __metaclass__ = somemeta

  an_attr = 12

  def bar(self):
      ...

  @classmethod
  def foo(cls):
      ...

      arguments would be : ( somemeta, "foo", (baseclass, baseofbase,..., object), {"an_attr":12, "bar": <function>, "foo": <bound class method>}

      you can modify any of these values before passing on to type
      """
      return type.__call__(mcs, name, bases, clsdict)


    def __init__(self, name, bases, clsdict):
      """ 
      called after type has been created. unlike in standard classes, __init__ method cannot modify the instance (cls) - and should be used for class validaton.
      """
      pass


    def __prepare__():
        """
        returns a dict or something that can be used as a namespace.
        the type will then attach methods and attributes from class definition to it.

        call order :

        somemeta.__new__ ->  type.__new__ -> type.__init__ -> somemeta.__init__ 
        """
        return dict()

    def mymethod(cls):
        """ works like a classmethod, but for class objects. Also, my method will not be visible to instances of cls.
        """
        pass

无论如何,这两个是最常用的钩子。元类非常强大,上面还没有列出元类的详尽用途。

type() 函数可以返回对象的类型或创建新类型,

例如,我们可以使用 type() 函数创建一个 Hi 类,而无需对类 Hi(object) 使用这种方式:

def func(self, name='mike'):
    print('Hi, %s.' % name)

Hi = type('Hi', (object,), dict(hi=func))
h = Hi()
h.hi()
Hi, mike.

type(Hi)
type

type(h)
__main__.Hi

除了使用 type() 动态创建类之外,您还可以控制类的创建行为并使用元类。

根据Python对象模型,类就是对象,因此类必须是另一个某个类的实例。默认情况下,Python 类是类型类的实例。也就是说,类型是大多数内置类的元类和用户定义类的元类。

class ListMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['add'] = lambda self, value: self.append(value)
        return type.__new__(cls, name, bases, attrs)

class CustomList(list, metaclass=ListMetaclass):
    pass

lst = CustomList()
lst.add('custom_list_1')
lst.add('custom_list_2')

lst
['custom_list_1', 'custom_list_2']

当我们在元类中传递关键字参数时,Magic 就会生效,它指示 Python 解释器通过 ListMetaclass 创建 CustomList。 新的 (),此时,我们可以修改类定义,例如添加一个新方法,然后返回修改后的定义。

除了已发布的答案之外,我可以说 metaclass 定义类的行为。因此,您可以显式设置元类。每当Python获得一个关键字时 class 然后它开始搜索 metaclass. 。如果未找到,则使用默认元类类型来创建类的对象。使用 __metaclass__ 属性,可以设置 metaclass 你的班级:

class MyClass:
   __metaclass__ = type
   # write here other method
   # write here one more method

print(MyClass.__metaclass__)

它会产生如下输出:

class 'type'

当然,您也可以创建自己的 metaclass 定义使用您的类创建的任何类的行为。

为此,您的默认设置 metaclass 类型类必须继承,因为这是主要的 metaclass:

class MyMetaClass(type):
   __metaclass__ = type
   # you can write here any behaviour you want

class MyTestClass:
   __metaclass__ = MyMetaClass

Obj = MyTestClass()
print(Obj.__metaclass__)
print(MyMetaClass.__metaclass__)

输出将是:

class '__main__.MyMetaClass'
class 'type'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top