Python 中的元类是什么?

骑猪看日落 2024-03-31 16:18 241阅读 0赞

问题描述:

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

解决方案1:

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

作为对象的类

在了解元类之前,您需要掌握 Python 中的类。 Python 对什么是类有一个非常奇特的想法,这是从 Smalltalk 语言中借来的。

在大多数语言中,类只是描述如何生成对象的代码片段。在 Python 中也是如此:

  1. >>> class ObjectCreator(object):
  2. ... pass
  3. ...
  4. >>> my_object = ObjectCreator()
  5. >>> print(my_object)
  6. <__main__.ObjectCreator object at 0x8974f2c>

但是类不仅仅是 Python 中的类。类也是对象。

是的,对象。

只要您使用关键字 class,Python 就会执行它并创建一个对象。该指令

  1. >>> class ObjectCreator(object):
  2. ... pass
  3. ...

在内存中创建一个名为 ObjectCreator 的对象。

这个对象(类)本身能够创建对象(实例),这就是它是类的原因。

但是,它仍然是一个对象,因此:

您可以将其分配给变量

你可以复制它

您可以为其添加属性

您可以将其作为函数参数传递

例如:

  1. >>> print(ObjectCreator) # you can print a class because it's an object
  2. >>> def echo(o):
  3. ... print(o)
  4. ...
  5. >>> echo(ObjectCreator) # you can pass a class as a parameter
  6. >>> print(hasattr(ObjectCreator, 'new_attribute'))
  7. False
  8. >>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class
  9. >>> print(hasattr(ObjectCreator, 'new_attribute'))
  10. True
  11. >>> print(ObjectCreator.new_attribute)
  12. foo
  13. >>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable
  14. >>> print(ObjectCreatorMirror.new_attribute)
  15. foo
  16. >>> print(ObjectCreatorMirror())
  17. <__main__.ObjectCreator object at 0x8997b4c>

动态创建类

由于类是对象,因此您可以像任何对象一样动态创建它们。

首先,您可以使用 class 在函数中创建一个类:

  1. >>> def choose_class(name):
  2. ... if name == 'foo':
  3. ... class Foo(object):
  4. ... pass
  5. ... return Foo # return the class, not an instance
  6. ... else:
  7. ... class Bar(object):
  8. ... pass
  9. ... return Bar
  10. ...
  11. >>> MyClass = choose_class('foo')
  12. >>> print(MyClass) # the function returns a class, not an instance
  13. >>> print(MyClass()) # you can create an object from this class
  14. <__main__.Foo object at 0x89c6d4c>

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

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

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

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

  1. >>> print(type(1))
  2. >>> print(type("1"))
  3. >>> print(type(ObjectCreator))
  4. >>> print(type(ObjectCreator()))

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

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

type 以这种方式工作:

  1. type(name, bases, attrs)

在哪里:

名称:类的名称

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

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

例如:

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

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

  1. >>> MyShinyClass = type('MyShinyClass', (), {
  2. }) # returns a class object
  3. >>> print(MyShinyClass)
  4. >>> print(MyShinyClass()) # create an instance with the class
  5. <__main__.MyShinyClass object at 0x8997cec>

您会注意到我们使用 MyShinyClass 作为类的名称和保存类引用的变量。它们可以不同,但没有理由使事情复杂化。

type 接受一个字典来定义类的属性。所以:

  1. >>> class Foo(object):
  2. ... bar = True

可以翻译成:

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

并用作普通类:

  1. >>> print(Foo)
  2. >>> print(Foo.bar)
  3. True
  4. >>> f = Foo()
  5. >>> print(f)
  6. <__main__.Foo object at 0x8a9b84c>
  7. >>> print(f.bar)
  8. True

当然,你可以继承它,所以:

  1. >>> class FooChild(Foo):
  2. ... pass

将会:

  1. >>> FooChild = type('FooChild', (Foo,), {
  2. })
  3. >>> print(FooChild)
  4. >>> print(FooChild.bar) # bar is inherited from Foo
  5. True

最终,你会想要为你的类添加方法。只需定义一个具有适当签名的函数并将其分配为属性。

  1. >>> def echo_bar(self):
  2. ... print(self.bar)
  3. ...
  4. >>> FooChild = type('FooChild', (Foo,), {
  5. 'echo_bar': echo_bar})
  6. >>> hasattr(Foo, 'echo_bar')
  7. False
  8. >>> hasattr(FooChild, 'echo_bar')
  9. True
  10. >>> my_foo = FooChild()
  11. >>> my_foo.echo_bar()
  12. True

并且你可以在动态创建类之后添加更多的方法,就像在正常创建的类对象中添加方法一样。

  1. >>> def echo_bar_more(self):
  2. ... print('yet another method')
  3. ...
  4. >>> FooChild.echo_bar_more = echo_bar_more
  5. >>> hasattr(FooChild, 'echo_bar_more')
  6. True

你知道我们要去哪里:在 Python 中,类是对象,你可以动态地创建一个类。

这就是 Python 在使用关键字 class 时所做的事情,它通过使用元类来做到这一点。

什么是元类(最后)

元类是创建类的“东西”。

你定义类是为了创建对象,对吧?

但是我们了解到 Python 类是对象。

好吧,元类是创建这些对象的原因。它们是班级的班级,您可以这样描绘它们:

  1. MyClass = MetaClass()
  2. my_object = MyClass()

您已经看到 type 允许您执行以下操作:

  1. MyClass = type('MyClass', (), {
  2. })

这是因为函数 type 实际上是一个元类。 type 是 Python 用于在幕后创建所有类的元类。

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

好吧,我想这是与 str(创建字符串对象的类)和 int(创建整数对象的类)的一致性问题。 type 只是创建类对象的类。

您可以通过检查 class 属性看到这一点。

一切,我的意思是一切,都是 Python 中的对象。这包括整数、字符串、函数和类。它们都是对象。所有这些都是从一个类创建的:

  1. >>> age = 35
  2. >>> age.__class__
  3. >>> name = 'bob'
  4. >>> name.__class__
  5. >>> def foo(): pass
  6. >>> foo.__class__
  7. >>> class Bar(object): pass
  8. >>> b = Bar()
  9. >>> b.__class__

现在,任何 classclass 是什么?

  1. >>> age.__class__.__class__
  2. >>> name.__class__.__class__
  3. >>> foo.__class__.__class__
  4. >>> b.__class__.__class__

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

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

type 是 Python 使用的内置元类,当然,您也可以创建自己的元类。

metaclass 属性

在 Python 2 中,您可以在编写类时添加 metaclass 属性(请参阅下一节了解 Python 3 语法):

  1. class Foo(object):
  2. __metaclass__ = something...
  3. [...]

如果您这样做,Python 将使用元类来创建类 Foo。

小心,这很棘手。

您先编写 class Foo(object),但尚未在内存中创建类对象 Foo。

Python 将在类定义中查找 metaclass。如果找到它,它将使用它来创建对象类 Foo。如果没有,它将使用 type 创建类。

多读几遍。

当你这样做时:

  1. class Foo(Bar):
  2. 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 中设置元类的语法已更改:

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

即不再使用__metaclass__ 属性,而是使用基类列表中的关键字参数。

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

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

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

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

自定义元类

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

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

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

这样,这个模块的所有类都将使用这个元类创建,我们只需要告诉元类将所有属性都转为大写即可。

幸运的是,metaclass 实际上可以是任何可调用的,它不需要是一个正式的类(我知道,名称中带有 ‘class’ 的东西不需要是一个类,去看看…但它很有帮助)。

所以我们将从一个简单的例子开始,使用一个函数。

  1. # the metaclass will automatically get passed the same argument
  2. # that you usually pass to `type`
  3. def upper_attr(future_class_name, future_class_parents, future_class_attrs):
  4. """
  5. Return a class object, with the list of its attribute turned
  6. into uppercase.
  7. """
  8. # pick up any attribute that doesn't start with '__' and uppercase it
  9. uppercase_attrs = {
  10. attr if attr.startswith("__") else attr.upper(): v
  11. for attr, v in future_class_attrs.items()
  12. }
  13. # let `type` do the class creation
  14. return type(future_class_name, future_class_parents, uppercase_attrs)
  15. __metaclass__ = upper_attr # this will affect all classes in the module
  16. class Foo(): # global __metaclass__ won't work with "object" though
  17. # but we can define __metaclass__ here instead to affect only this class
  18. # and this will work with "object" children
  19. bar = 'bip'

让我们检查:

  1. >>> hasattr(Foo, 'bar')
  2. False
  3. >>> hasattr(Foo, 'BAR')
  4. True
  5. >>> Foo.BAR
  6. 'bip'

现在,让我们做同样的事情,但使用一个真正的类作为元类:

  1. # remember that `type` is actually a class like `str` and `int`
  2. # so you can inherit from it
  3. class UpperAttrMetaclass(type):
  4. # __new__ is the method called before __init__
  5. # it's the method that creates the object and returns it
  6. # while __init__ just initializes the object passed as parameter
  7. # you rarely use __new__, except when you want to control how the object
  8. # is created.
  9. # here the created object is the class, and we want to customize it
  10. # so we override __new__
  11. # you can do some stuff in __init__ too if you wish
  12. # some advanced use involves overriding __call__ as well, but we won't
  13. # see this
  14. def __new__(upperattr_metaclass, future_class_name,
  15. future_class_parents, future_class_attrs):
  16. uppercase_attrs = {
  17. attr if attr.startswith("__") else attr.upper(): v
  18. for attr, v in future_class_attrs.items()
  19. }
  20. return type(future_class_name, future_class_parents, uppercase_attrs)

让我们重写上面的内容,但是现在我们知道它们的含义,使用更短和更真实的变量名称:

  1. class UpperAttrMetaclass(type):
  2. def __new__(cls, clsname, bases, attrs):
  3. uppercase_attrs = {
  4. attr if attr.startswith("__") else attr.upper(): v
  5. for attr, v in attrs.items()
  6. }
  7. return type(clsname, bases, uppercase_attrs)

您可能已经注意到额外的参数 cls。它没有什么特别之处:new 总是接收定义它的类作为第一个参数。就像您有 self 用于接收实例作为第一个参数的普通方法,或者为类方法定义类。

但这不是正确的 OOP。我们直接调用 type,而不是覆盖或调用父级的 new。让我们这样做:

  1. class UpperAttrMetaclass(type):
  2. def __new__(cls, clsname, bases, attrs):
  3. uppercase_attrs = {
  4. attr if attr.startswith("__") else attr.upper(): v
  5. for attr, v in attrs.items()
  6. }
  7. return type.__new__(cls, clsname, bases, uppercase_attrs)

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

  1. class UpperAttrMetaclass(type):
  2. def __new__(cls, clsname, bases, attrs):
  3. uppercase_attrs = {
  4. attr if attr.startswith("__") else attr.upper(): v
  5. for attr, v in attrs.items()
  6. }
  7. return super(UpperAttrMetaclass, cls).__new__(
  8. cls, clsname, bases, uppercase_attrs)

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

  1. class Foo(object, metaclass=MyMetaclass, kwarg1=value1):
  2. ...

它在元类中转换为 this 以使用它:

  1. class MyMetaclass(type):
  2. def __new__(cls, clsname, bases, dct, kwargs1=default):
  3. ...

而已。元类真的没有更多的东西了。

使用元类的代码复杂背后的原因不是因为元类,而是因为您通常使用元类来做一些扭曲的事情,依赖于自省、操作继承、dict 等变量等。

事实上,元类对于做黑魔法特别有用,因此也很复杂。但就其本身而言,它们很简单:

拦截类创建

修改类

返回修改后的类

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

既然 metaclass 可以接受任何可调用的,为什么要使用一个类,因为它显然更复杂?

这样做有几个原因:

意图很明确。当你阅读 UpperAttrMetaclass(type) 时,你知道接下来会发生什么

您可以使用 OOP。元类可以继承元类,覆盖父方法。元类甚至可以使用元类。

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

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

您可以挂接 newinitcall。这将允许你做不同的事情,即使通常你可以在 new 中完成所有事情,有些人只是更喜欢使用 init

这些被称为元类,该死!一定是什么意思!

为什么要使用元类?

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

好吧,通常你不会:

元类是更深层次的魔法,99% 的用户都不应该担心它。如果你想知道你是否需要它们,你就不需要(真正需要它们的人肯定知道他们需要它们,并且不需要解释为什么)。

Python 大师蒂姆·彼得斯

元类的主要用例是创建 API。一个典型的例子是 Django ORM。它允许您定义如下内容:

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

但如果你这样做:

  1. person = Person(name='bob', age='35')
  2. print(person.age)

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

这是可能的,因为 models.Model 定义了 metaclass,并且它使用了一些魔法,将您刚刚使用简单语句定义的 Person 变成了数据库字段的复杂挂钩。

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

最后一个字

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

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

  1. >>> class Foo(object): pass
  2. >>> id(Foo)
  3. 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,以实现或更改类的行为方式。

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

  1. def make_hook(f):
  2. """Decorator to turn 'foo' method into '__foo__'"""
  3. f.is_hook = 1
  4. return f
  5. class MyType(type):
  6. def __new__(mcls, name, bases, attrs):
  7. if name.startswith('None'):
  8. return None
  9. # Go over attributes and see if they should be renamed.
  10. newattrs = {
  11. }
  12. for attrname, attrvalue in attrs.iteritems():
  13. if getattr(attrvalue, 'is_hook', 0):
  14. newattrs['__%s__' % attrname] = attrvalue
  15. else:
  16. newattrs[attrname] = attrvalue
  17. return super(MyType, mcls).__new__(mcls, name, bases, newattrs)
  18. def __init__(self, name, bases, attrs):
  19. super(MyType, self).__init__(name, bases, attrs)
  20. # classregistry.register(self, self.interfaces)
  21. print "Would register class %s now." % self
  22. def __add__(self, other):
  23. class AutoClass(self, other):
  24. pass
  25. return AutoClass
  26. # Alternatively, to autogenerate the classname as well as the class:
  27. # return type(self.__name__ + other.__name__, (self, other), {
  28. })
  29. def unregister(self):
  30. # classregistry.unregister(self)
  31. print "Would unregister class %s now." % self
  32. class MyObject:
  33. __metaclass__ = MyType
  34. class NoneSample(MyObject):
  35. pass
  36. # Will print "NoneType None"
  37. print type(NoneSample), repr(NoneSample)
  38. class Example(MyObject):
  39. def __init__(self, value):
  40. self.value = value
  41. @make_hook
  42. def add(self, other):
  43. return self.__class__(self.value + other.value)
  44. # Will unregister the class
  45. Example.unregister()
  46. inst = Example(10)
  47. # Will fail with an AttributeError
  48. #inst.unregister()
  49. print inst + inst
  50. class Sibling(MyObject):
  51. pass
  52. ExampleSibling = Example + Sibling
  53. # ExampleSibling is now a subclass of both Example and Sibling (with no
  54. # content of its own) although it will believe it's called 'AutoClass'
  55. print ExampleSibling
  56. 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 中略有不同。

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

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

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

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

  1. class ThisIsTheName(Bases, Are, Here):
  2. All_the_code_here
  3. def doesIs(create, a):
  4. dict

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

  1. def test_metaclass(name, bases, dict):
  2. print 'The Class Name is', name
  3. print 'The Class Bases are', bases
  4. print 'The dict has', len(dict), 'elems, the keys are', dict.keys()
  5. return "yellow"
  6. class TestName(object, None, int, 1):
  7. __metaclass__ = test_metaclass
  8. foo = 1
  9. def baz(self, arr):
  10. pass
  11. print 'TestName = ', repr(TestName)
  12. # output =>
  13. The Class Name is TestName
  14. The Class Bases are (, None, , 1)
  15. The dict has 4 elems, the keys are ['baz', '__module__', 'foo', '__metaclass__']
  16. TestName = 'yellow'

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

  1. def init_attributes(name, bases, dict):
  2. if 'attributes' in dict:
  3. for attr in dict['attributes']:
  4. dict[attr] = None
  5. return type(name, bases, dict)
  6. class Initialised(object):
  7. __metaclass__ = init_attributes
  8. attributes = ['foo', 'bar', 'baz']
  9. print 'foo =>', Initialised.foo
  10. # output=>
  11. foo => None

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

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

  1. class MetaSingleton(type):
  2. instance = None
  3. def __call__(cls, *args, **kw):
  4. if cls.instance is None:
  5. cls.instance = super(MetaSingleton, cls).__call__(*args, **kw)
  6. return cls.instance
  7. class Foo(object):
  8. __metaclass__ = MetaSingleton
  9. a = Foo()
  10. b = Foo()
  11. assert a is b

解决方案4:

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

其他人已经解释了元类如何工作以及它们如何适应 Python 类型系统。这是它们可以用于什么的示例。在我编写的测试框架中,我想跟踪定义类的顺序,以便以后可以按此顺序实例化它们。我发现使用元类最容易做到这一点。

  1. class MyMeta(type):
  2. counter = 0
  3. def __init__(cls, name, bases, dic):
  4. type.__init__(cls, name, bases, dic)
  5. cls._order = MyMeta.counter
  6. MyMeta.counter += 1
  7. class MyType(object): # Python 2
  8. __metaclass__ = MyMeta
  9. class MyType(metaclass=MyMeta): # Python 3
  10. pass

任何属于 MyType 子类的东西都会获得一个类属性 _order,该属性记录了定义类的顺序。

谢谢你的例子。为什么你发现这比从 MyBase 继承更容易,它的 __init__(self) 是 type(self)._order = MyBase.counter; MyBase.counter += 1 ?

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

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

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

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

解决方案5:

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

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

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

  1. class Person(models.Model):
  2. first_name = models.CharField(max_length=30)
  3. 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:元类实例化并定义类的行为,就像类实例化并定义实例的行为一样。

伪代码:

  1. >>> Class(...)
  2. instance

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

  1. >>> Metaclass(...)
  2. Class

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

  1. >>> type('Foo', (object,), {
  2. }) # 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:

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

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

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

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

  1. class Foo(object):
  2. 'demo'

您实例化一个类对象。

  1. >>> Foo
  2. >>> isinstance(Foo, type), isinstance(Foo, object)
  3. (True, True)

这与使用适当的参数在功能上调用 type 并将结果分配给该名称的变量相同:

  1. name = 'Foo'
  2. bases = (object,)
  3. namespace = {
  4. '__doc__': 'demo'}
  5. Foo = type(name, bases, namespace)

请注意,有些东西会自动添加到 dict,即命名空间:

  1. >>> Foo.__dict__
  2. dict_proxy({
  3. '__dict__': ,
  4. '__module__': '__main__', '__weakref__': , '__doc__': 'demo'})

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

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

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

…但我离题了。)

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

这是类的默认 repr

  1. >>> Foo

默认情况下,我们在编写 Python 对象时可以做的最有价值的事情之一就是为其提供良好的 repr。当我们调用 help(repr) 时,我们了解到有一个很好的 repr 测试还需要一个相等性测试 - obj == eval(repr(obj))。以下对我们类型类的类实例的 repreq 的简单实现为我们提供了一个可以改进类的默认 repr 的演示:

  1. class Type(type):
  2. def __repr__(cls):
  3. """
  4. >>> Baz
  5. Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
  6. >>> eval(repr(Baz))
  7. Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
  8. """
  9. metaname = type(cls).__name__
  10. name = cls.__name__
  11. parents = ', '.join(b.__name__ for b in cls.__bases__)
  12. if parents:
  13. parents += ','
  14. namespace = ', '.join(': '.join(
  15. (repr(k), repr(v) if not isinstance(v, type) else v.__name__))
  16. for k, v in cls.__dict__.items())
  17. return '{
  18. 0}(\'{
  19. 1}\', ({
  20. 2}), {
  21. {
  22. {
  23. 3}}})'.format(metaname, name, parents, namespace)
  24. def __eq__(cls, other):
  25. """
  26. >>> Baz == eval(repr(Baz))
  27. True
  28. """
  29. return (cls.__name__, cls.__bases__, cls.__dict__) == (
  30. other.__name__, other.__bases__, other.__dict__)

所以现在当我们用这个元类创建一个对象时,在命令行中回显的 repr 提供了一个比默认值少得多的丑陋景象:

  1. >>> class Bar(object): pass
  2. >>> Baz = Type('Baz', (Foo, Bar,), {
  3. '__module__': '__main__', '__doc__': None})
  4. >>> Baz
  5. Type('Baz', (Foo, Bar,), {
  6. '__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:

  1. from collections import OrderedDict
  2. class OrderedType(Type):
  3. @classmethod
  4. def __prepare__(metacls, name, bases, **kwargs):
  5. return OrderedDict()
  6. def __new__(cls, name, bases, namespace, **kwargs):
  7. result = Type.__new__(cls, name, bases, dict(namespace))
  8. result.members = tuple(namespace)
  9. return result

和用法:

  1. class OrderedMethodsObject(object, metaclass=OrderedType):
  2. def method1(self): pass
  3. def method2(self): pass
  4. def method3(self): pass
  5. def method4(self): pass

现在我们记录了这些方法(和其他类属性)的创建顺序:

  1. >>> OrderedMethodsObject.members
  2. ('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4')

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

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

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

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

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

解决方案8:

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

Python 3 更新

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

prepare,和

新的

prepare 允许您提供自定义映射(例如 OrderedDict)以在创建类时用作命名空间。您必须返回您选择的任何命名空间的实例。如果您不实现 prepare,则使用普通的 dict。

new 负责最终类的实际创建/修改。

一个简单的、什么都不做的额外元类会喜欢:

  1. class Meta(type):
  2. def __prepare__(metaclass, cls, bases):
  3. return dict()
  4. def __new__(metacls, cls, bases, clsdict):
  5. return super().__new__(metacls, cls, bases, clsdict)

一个简单的例子:

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

  1. class Person:
  2. weight = ValidateType('weight', int)
  3. age = ValidateType('age', int)
  4. name = ValidateType('name', str)

如您所见,您必须重复两次属性名称。这使得拼写错误和恼人的错误成为可能。

一个简单的元类可以解决这个问题:

  1. class Person(metaclass=Validator):
  2. weight = ValidateType(int)
  3. age = ValidateType(int)
  4. name = ValidateType(str)

这是元类的样子(不使用 prepare,因为它不是必需的):

  1. class Validator(type):
  2. def __new__(metacls, cls, bases, clsdict):
  3. # search clsdict looking for ValidateType descriptors
  4. for name, attr in clsdict.items():
  5. if isinstance(attr, ValidateType):
  6. attr.name = name
  7. attr.attr = '_' + name
  8. # create final class and return it
  9. return super().__new__(metacls, cls, bases, clsdict)

运行示例:

  1. p = Person()
  2. p.weight = 9
  3. print(p.weight)
  4. p.weight = '9'

产生:

  1. 9
  2. Traceback (most recent call last):
  3. File "simple_meta.py", line 36, in
  4. p.weight = '9'
  5. File "simple_meta.py", line 24, in __set__
  6. (self.name, self.type, value))
  7. TypeError: weight must be of type(s) (got '9')

注意:这个例子很简单,它也可以用一个类装饰器来完成,但大概一个实际的元类会做更多的事情。

‘ValidateType’ 类供参考:

  1. class ValidateType:
  2. def __init__(self, type):
  3. self.name = None # will be set by metaclass
  4. self.attr = None # will be set by metaclass
  5. self.type = type
  6. def __get__(self, inst, cls):
  7. if inst is None:
  8. return self
  9. else:
  10. return inst.__dict__[self.attr]
  11. def __set__(self, inst, value):
  12. if not isinstance(value, self.type):
  13. raise TypeError('%s must be of type(s) %s (got %r)' %
  14. (self.name, self.type, value))
  15. else:
  16. 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 编程,您最终会偶然发现如下所示的代码:

  1. # define a class
  2. class SomeClass(object):
  3. # ...
  4. # some definition here ...
  5. # ...
  6. # create an instance of it
  7. instance = SomeClass()
  8. # then call the object as if it's a function
  9. result = instance('foo', 'bar')

当您在类上实现 call() 魔术方法时,后者是可能的。

  1. class SomeClass(object):
  2. # ...
  3. # some definition here ...
  4. # ...
  5. def __call__(self, foo, bar):
  6. return bar + foo

当类的实例用作可调用对象时,会调用 call() 方法。但正如我们从之前的回答中看到的,一个类本身就是一个元类的实例,所以当我们将该类用作可调用对象时(即当我们创建它的实例时),我们实际上是在调用它的元类的 call() 方法.在这一点上,大多数 Python 程序员有点困惑,因为他们被告知在创建像 instance = SomeClass() 这样的实例时,您正在调用它的 init() 方法。一些深入挖掘的人知道,在 init() 之前有 new()。好吧,今天揭示了另一层真相,在 new() 之前有元类__call__()。

我们具体从创建类实例的角度来研究方法调用链。

这是一个元类,它准确记录实例创建之前的时刻和即将返回它的时刻。

  1. class Meta_1(type):
  2. def __call__(cls):
  3. print "Meta_1.__call__() before creating an instance of ", cls
  4. instance = super(Meta_1, cls).__call__()
  5. print "Meta_1.__call__() about to return instance."
  6. return instance

这是一个使用该元类的类

  1. class Class_1(object):
  2. __metaclass__ = Meta_1
  3. def __new__(cls):
  4. print "Class_1.__new__() before creating an instance."
  5. instance = super(Class_1, cls).__new__(cls)
  6. print "Class_1.__new__() about to return instance."
  7. return instance
  8. def __init__(self):
  9. print "entering Class_1.__init__() for instance initialization."
  10. super(Class_1,self).__init__()
  11. print "exiting Class_1.__init__()."

现在让我们创建一个 Class_1 的实例

  1. instance = Class_1()
  2. # Meta_1.__call__() before creating an instance of .
  3. # Class_1.__new__() before creating an instance.
  4. # Class_1.__new__() about to return instance.
  5. # entering Class_1.__init__() for instance initialization.
  6. # exiting Class_1.__init__().
  7. # Meta_1.__call__() about to return instance.

请注意,上面的代码实际上除了记录任务之外没有做任何事情。每个方法都将实际工作委托给其父级的实现,从而保持默认行为。由于 type 是 Meta_1 的父类(type 是默认的父元类)并且考虑到上面输出的排序顺序,我们现在对 type.call() 的伪实现有一个线索:

  1. class type:
  2. def __call__(cls, *args, **kwarg):
  3. # ... maybe a few things done to cls here
  4. # then we call __new__() on the class to create an instance
  5. instance = cls.__new__(cls, *args, **kwargs)
  6. # ... maybe a few things done to the instance here
  7. # then we initialize the instance with its __init__() method
  8. instance.__init__(*args, **kwargs)
  9. # ... maybe a few more things done to instance here
  10. # then we return it
  11. return instance

我们可以看到元类的 call() 方法是第一个被调用的方法。然后它将实例的创建委托给类的 new() 方法,并将初始化委托给实例的 init()。它也是最终返回实例的那个。

从上面可以看出,元类的 call() 也有机会决定是否最终会调用 Class_1.new() 或 Class_1.init()。在其执行过程中,它实际上可以返回一个没有被这两种方法接触过的对象。以单例模式的这种方法为例:

  1. class Meta_2(type):
  2. singletons = {
  3. }
  4. def __call__(cls, *args, **kwargs):
  5. if cls in Meta_2.singletons:
  6. # we return the only instance and skip a call to __new__()
  7. # and __init__()
  8. print ("{} singleton returning from Meta_2.__call__(), "
  9. "skipping creation of new instance.".format(cls))
  10. return Meta_2.singletons[cls]
  11. # else if the singleton isn't present we proceed as usual
  12. print "Meta_2.__call__() before creating an instance."
  13. instance = super(Meta_2, cls).__call__(*args, **kwargs)
  14. Meta_2.singletons[cls] = instance
  15. print "Meta_2.__call__() returning new instance."
  16. return instance
  17. class Class_2(object):
  18. __metaclass__ = Meta_2
  19. def __new__(cls, *args, **kwargs):
  20. print "Class_2.__new__() before creating instance."
  21. instance = super(Class_2, cls).__new__(cls)
  22. print "Class_2.__new__() returning instance."
  23. return instance
  24. def __init__(self, *args, **kwargs):
  25. print "entering Class_2.__init__() for initialization."
  26. super(Class_2, self).__init__()
  27. print "exiting Class_2.__init__()."

让我们观察在重复尝试创建 Class_2 类型的对象时会发生什么

  1. a = Class_2()
  2. # Meta_2.__call__() before creating an instance.
  3. # Class_2.__new__() before creating instance.
  4. # Class_2.__new__() returning instance.
  5. # entering Class_2.__init__() for initialization.
  6. # exiting Class_2.__init__().
  7. # Meta_2.__call__() returning new instance.
  8. b = Class_2()
  9. # singleton returning from Meta_2.__call__(), skipping creation of new instance.
  10. c = Class_2()
  11. # singleton returning from Meta_2.__call__(), skipping creation of new instance.
  12. a is b is c # True

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

解决方案10:

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

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

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

  1. #!/usr/bin/env python
  2. # Copyright (C) 2013-2014 Craig Phillips. All rights reserved.
  3. # This requires some explaining. The point of this metaclass excercise is to
  4. # create a static abstract class that is in one way or another, dormant until
  5. # queried. I experimented with creating a singlton on import, but that did
  6. # not quite behave how I wanted it to. See now here, we are creating a class
  7. # called GsyncOptions, that on import, will do nothing except state that its
  8. # class creator is GsyncOptionsType. This means, docopt doesn't parse any
  9. # of the help document, nor does it start processing command line options.
  10. # So importing this module becomes really efficient. The complicated bit
  11. # comes from requiring the GsyncOptions class to be static. By that, I mean
  12. # any property on it, may or may not exist, since they are not statically
  13. # defined; so I can't simply just define the class with a whole bunch of
  14. # properties that are @property @staticmethods.
  15. #
  16. # So here's how it works:
  17. #
  18. # Executing 'from libgsync.options import GsyncOptions' does nothing more
  19. # than load up this module, define the Type and the Class and import them
  20. # into the callers namespace. Simple.
  21. #
  22. # Invoking 'GsyncOptions.debug' for the first time, or any other property
  23. # causes the __metaclass__ __getattr__ method to be called, since the class
  24. # is not instantiated as a class instance yet. The __getattr__ method on
  25. # the type then initialises the class (GsyncOptions) via the __initialiseClass
  26. # method. This is the first and only time the class will actually have its
  27. # dictionary statically populated. The docopt module is invoked to parse the
  28. # usage document and generate command line options from it. These are then
  29. # paired with their defaults and what's in sys.argv. After all that, we
  30. # setup some dynamic properties that could not be defined by their name in
  31. # the usage, before everything is then transplanted onto the actual class
  32. # object (or static class GsyncOptions).
  33. #
  34. # Another piece of magic, is to allow command line options to be set in
  35. # in their native form and be translated into argparse style properties.
  36. #
  37. # Finally, the GsyncListOptions class is actually where the options are
  38. # stored. This only acts as a mechanism for storing options as lists, to
  39. # allow aggregation of duplicate options or options that can be specified
  40. # multiple times. The __getattr__ call hides this by default, returning the
  41. # last item in a property's list. However, if the entire list is required,
  42. # calling the 'list()' method on the GsyncOptions class, returns a reference
  43. # to the GsyncListOptions class, which contains all of the same properties
  44. # but as lists and without the duplication of having them as both lists and
  45. # static singlton values.
  46. #
  47. # So this actually means that GsyncOptions is actually a static proxy class...
  48. #
  49. # ...And all this is neatly hidden within a closure for safe keeping.
  50. def GetGsyncOptionsType():
  51. class GsyncListOptions(object):
  52. __initialised = False
  53. class GsyncOptionsType(type):
  54. def __initialiseClass(cls):
  55. if GsyncListOptions._GsyncListOptions__initialised: return
  56. from docopt import docopt
  57. from libgsync.options import doc
  58. from libgsync import __version__
  59. options = docopt(
  60. doc.__doc__ % __version__,
  61. version = __version__,
  62. options_first = True
  63. )
  64. paths = options.pop('', None)
  65. setattr(cls, "destination_path", paths.pop() if paths else None)
  66. setattr(cls, "source_paths", paths)
  67. setattr(cls, "options", options)
  68. for k, v in options.iteritems():
  69. setattr(cls, k, v)
  70. GsyncListOptions._GsyncListOptions__initialised = True
  71. def list(cls):
  72. return GsyncListOptions
  73. def __getattr__(cls, name):
  74. cls.__initialiseClass()
  75. return getattr(GsyncListOptions, name)[-1]
  76. def __setattr__(cls, name, value):
  77. # Substitut option names: --an-option-name for an_option_name
  78. import re
  79. name = re.sub(r'^__', "", re.sub(r'-', "_", name))
  80. listvalue = []
  81. # Ensure value is converted to a list type for GsyncListOptions
  82. if isinstance(value, list):
  83. if value:
  84. listvalue = [] + value
  85. else:
  86. listvalue = [ None ]
  87. else:
  88. listvalue = [ value ]
  89. type.__setattr__(GsyncListOptions, name, listvalue)
  90. # Cleanup this module to prevent tinkering.
  91. import sys
  92. module = sys.modules[__name__]
  93. del module.__dict__['GetGsyncOptionsType']
  94. return GsyncOptionsType
  95. # Our singlton abstract proxy class.
  96. class GsyncOptions(object):
  97. __metaclass__ = GetGsyncOptionsType()

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

解决方案11:

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

tl;dr 版本

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

类的 type() 是它的元类。

要使用元类:

  1. class Foo(object):
  2. __metaclass__ = MyMetaClass

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

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

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

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

发表评论

表情:
评论列表 (有 0 条评论,241人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python什么

    在Python中,元组(Tuple)是一种有序、不可变的数据结构。元组可以包含多个元素,这些元素可以是不同类型的数据,例如整数、字符串、浮点数等。与列表(List)不同,元组一

    相关 什么注解

    什么是元注解 元注解是可以注解到注解上的注解,或者说元注解是一种基本注解,但是它能够应用到其它的注解上面。它的作用和目的就是给其他普通的标签进行解释说明的。 元标签有