在Python中,什么是元类,我们用它们做什么?
Python中的元类是什么?
类作为对象
在理解元类之前,您需要掌握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, bases, attrs)
哪里:
name
:类的名称bases
:父类的元组(对于继承,可以为空)attrs
:包含属性名称和值的字典
例如:
>>> 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使用元类在幕后创建所有类。
现在你想知道"为什么它是用小写写的,而不是Type
?"
好吧,我想这是一个与str
一致的问题,这个类创建
字符串对象,以及int
创建整数对象的类。 type
是
只是创建类对象的类。
您可以通过检查__class__
属性看到这一点。
一切,我的意思是一切,都是Python中的一个对象。 包括整数, 字符串,函数和类。 所有这些都是对象。 他们都有 从类创建:
>>> 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__
属性
在Python2中,您可以在编写类时添加__metaclass__
属性(有关Python3语法,请参阅下一节):
class Foo(object):
__metaclass__ = something...
[...]
如果这样做,Python将使用元类来创建类__metaclass__
。
小心点,这很棘手。
你先写class Foo(object)
,但是类对象__metaclass__
没有创建
还在记忆中。
Python将在类定义中查找__metaclass__
。 如果找到了,
它将使用它来创建对象类__metaclass__
。 如果没有,它将使用
type
来创建类。
读了好几遍。
当你这样做的时候:
class Foo(Bar):
pass
Python执行以下操作:
__metaclass__
中是否有__metaclass__
属性?
如果是,通过使用__metaclass__
中的内容,在内存中创建一个类对象(我说的是一个类对象,留在这里),名称为__metaclass__
。
如果Python找不到__metaclass__
,它会在模块级别寻找一个__metaclass__
,并尝试做同样的事情(但仅限于不继承任何东西的类,基本上是旧式类)。
然后,如果它根本找不到任何__metaclass__
,它将使用Bar
的(第一个父)自己的元类(可能是默认的type
)来创建类对象。
这里要注意,__metaclass__
属性不会被继承,父(Bar.__class__
)的元类会被继承。 如果Bar
使用__metaclass__
属性创建Bar
与type()
(而不是type.__new__()
),子类将不会继承该行为。
现在最大的问题是,你可以在__metaclass__
中放什么?
答案是可以创建类的东西。
什么可以创建一个类? type
,或任何子类或使用它的东西。
Python3中的元类
在Python3中更改了设置元类的语法:
class Foo(object, metaclass=something):
...
即不再使用__metaclass__
属性,在基类列表中使用关键字参数。
但是元类的行为保持基本相同。
在Python3中添加到元类的一件事是,您还可以将属性作为关键字参数传递到元类中,就像这样:
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)
哦,在Python3中,如果您使用关键字参数进行此调用,如下所示:
class Foo(object, metaclass=MyMetaclass, kwarg1=value1):
...
它在元类中转换为this来使用它:
class MyMetaclass(type):
def __new__(cls, clsname, bases, dct, kwargs1=default):
...
就这样。 真的没有什么更多关于元类。
使用元类的代码的复杂性背后的原因不是因为
对于元类,这是因为你通常使用元类来做扭曲的东西
依靠内省,操纵继承,vars如__dict__
等。
事实上,元类对黑魔法特别有用,因此 复杂的东西。 但就其本身而言,它们很简单:
- 拦截类创建
- 修改类
- 返回修改后的类
为什么你会使用元类类而不是函数?
既然__metaclass__
可以接受任何callable,为什么你会使用一个类
因为它显然更复杂?
这样做有几个原因:
- 意图是明确的。 当你读
UpperAttrMetaclass(type)
时,你知道 接下来会发生什么? - 您可以使用OOP。 元类可以继承自元类,复盖父方法。 元类甚至可以使用元类。
- 如果您指定了元类,则类的子类将是其元类的实例,但没有使用元类函数。
- 您可以更好地构建代码。 你永远不会将元类用于像上面的例子那样微不足道的事情。 通常是为了一些复杂的事情。 能够制作多个方法并将它们分组到一个类中对于使代码更易于阅读非常有用。
- 你可以勾上
__new__
,__init__
和__call__
。 这将允许你做不同的事情,即使通常你可以做这一切__new__
, 有些人只是更舒适地使用__init__
。 - 这些被称为元类,该死! 这一定意味着什么!
你为什么要使用元类?
现在是个大问题。 你为什么要使用一些晦涩难懂的容易出错的功能?
通常你不会:
元类是更深层次的魔法。 99%的用户永远不应该担心它。 如果你想知道你是否需要它们, 你没有(那些真正的人) 需要他们肯定地知道 他们需要他们,不需要 解释为什么)。
Python大师Tim Peters
元类的主要用例是创建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%的时间,你根本不需要班级改变。
所有回答
注意,这个答案是针对Python2的。x正如2008年写的那样,元类在3中略有不同。x.
元类是使"类"工作的秘密酱汁。 新样式对象的默认元类称为"类型"。
class type(object)
| type(object) -> the object's type
| type(name, bases, dict) -> a new type
元类取3个args。 'name','bases'和'dict'
这里是秘密开始的地方。 在此示例类定义中查找name,bases和dict来自何处。
class ThisIsTheName(Bases, Are, Here):
All_the_code_here
def doesIs(create, a):
dict
让我们定义一个元类,它将演示'class:'如何调用它。
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'
现在,一个实际上意味着什么的例子,这将自动使列表中的变量"属性"设置在类上,并设置为None。
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
的子类。
这是一个更具体的例子,展示了如何子类化'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
其他人已经解释了元类如何工作以及它们如何融入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
子类的东西都会得到一个class属性_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%。
什么是元类? 你用它们做什么?
Tldr:元类实例化并定义类的行为,就像类实例化并定义实例的行为一样。
伪代码:
>>> 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'>
当您编写类定义并执行它时,它使用元类来实例化类对象(反过来,它将用于实例化该类的实例)。
正如我们可以使用类定义来改变自定义对象实例的行为方式一样,我们可以使用元类类定义来改变类对象的行为方式。
它们可以用于什么? 从文档:
元类的潜在用途是无限的。 已经探索的一些想法包括日志记录,接口检查,自动委派,自动属性创建,代理,框架和自动资源锁定/同步。
尽管如此,通常鼓励用户避免使用元类,除非绝对必要。
每次创建类时都使用元类:
当你写一个类定义,例如,像这样,
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)
时,我们了解到有一个很好的测试a__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__
执行此操作,如果在Python3中实现,则返回类的命名空间dict:
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>})
Python3更新
在元类中有(在这一点上)两个关键方法:
__prepare__
,和__new__
__prepare__
允许您提供自定义映射(例如anOrderedDict
),以便在创建类时用作命名空间。 您必须返回您选择的任何命名空间的实例。 如果不实现__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)
一个简单的例子:
假设你想要一些简单的验证代码在你的属性上运行-就像它必须始终是anint
或astr
一样。 如果没有元类,您的类将看起来像:
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程序员都有点困惑,因为他们被告知,当创建这样的实例时,你正在调用它的
__init__()
方法。 一些深入挖掘的人知道,在
__init__()
之前有
__new__()
。 今天,在元类出现之前,另一层真理正在被揭示出来。
让我们具体从创建类实例的角度来研究方法调用链。
这是一个元类,它准确地记录实例创建前的那一刻以及它即将返回它的那一刻。
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
我们可以看到metaclass'
__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
元类是一个告诉如何创建(一些)其他类的类。
这是我看到元类作为我的问题的解决方案的情况: 我有一个非常复杂的问题,可能可以以不同的方式解决,但我选择使用元类来解决它。 由于复杂性,它是我编写的少数几个模块之一,其中模块中的注释超过了已编写的代码量。 在这儿。..
#!/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()
Tl;dr版本
type(obj)
函数获取对象的类型。
类的type()
是它的元类。
使用元类:
class Foo(object):
__metaclass__ = MyMetaClass
type
是它自己的元类。 类的类是元类--类的主体是传递给用于构造类的元类的参数。
在这里您可以阅读有关如何使用元类自定义类构造的信息。
type
实际上是一个metaclass
--创建另一个类的类。
大多数metaclass
是type
的子类。 metaclass
接收new
类作为其第一个参数,并提供对类对象的访问,其详细信息如下所述:
>>> 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
的执行。
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
无论如何,这两个是最常用的钩子。 metaclassing是强大的,上面是远没有和详尽的metaclassing用途列表。
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类是type类的实例。 也就是说,type是大多数内置类的元类和用户定义类的元类。
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']
魔术将生效当我们在metaclass中传递关键字参数时,它指示Python解释器通过ListMetaclass创建CustomList。 new(),此时,我们可以修改类定义,例如,并添加一个新方法,然后返回修改后的定义。
除了发布的答案之外,我可以说ametaclass
定义了类的行为。 所以,你可以明确地设置你的元类。 每当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
类型类,因为这是mainmetaclass
:
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'
请注意,在python3.6中引入了一个新的dunder方法__init_subclass__(cls, **kwargs)
来替换元类的许多常见用例。 创建定义类的子类时调用Is。 请参阅python文档。
这是它可用于的另一个例子:
- 您可以使用
metaclass
更改其实例(类)的功能。
class MetaMemberControl(type):
__slots__ = ()
@classmethod
def __prepare__(mcs, f_cls_name, f_cls_parents, # f_cls means: future class
meta_args=None, meta_options=None): # meta_args and meta_options is not necessarily needed, just so you know.
f_cls_attr = dict()
if not "do something or if you want to define your cool stuff of dict...":
return dict(make_your_special_dict=None)
else:
return f_cls_attr
def __new__(mcs, f_cls_name, f_cls_parents, f_cls_attr,
meta_args=None, meta_options=None):
original_getattr = f_cls_attr.get('__getattribute__')
original_setattr = f_cls_attr.get('__setattr__')
def init_getattr(self, item):
if not item.startswith('_'): # you can set break points at here
alias_name = '_' + item
if alias_name in f_cls_attr['__slots__']:
item = alias_name
if original_getattr is not None:
return original_getattr(self, item)
else:
return super(eval(f_cls_name), self).__getattribute__(item)
def init_setattr(self, key, value):
if not key.startswith('_') and ('_' + key) in f_cls_attr['__slots__']:
raise AttributeError(f"you can't modify private members:_{key}")
if original_setattr is not None:
original_setattr(self, key, value)
else:
super(eval(f_cls_name), self).__setattr__(key, value)
f_cls_attr['__getattribute__'] = init_getattr
f_cls_attr['__setattr__'] = init_setattr
cls = super().__new__(mcs, f_cls_name, f_cls_parents, f_cls_attr)
return cls
class Human(metaclass=MetaMemberControl):
__slots__ = ('_age', '_name')
def __init__(self, name, age):
self._name = name
self._age = age
def __getattribute__(self, item):
"""
is just for IDE recognize.
"""
return super().__getattribute__(item)
""" with MetaMemberControl then you don't have to write as following
@property
def name(self):
return self._name
@property
def age(self):
return self._age
"""
def test_demo():
human = Human('Carson', 27)
# human.age = 18 # you can't modify private members:_age <-- this is defined by yourself.
# human.k = 18 # 'Human' object has no attribute 'k' <-- system error.
age1 = human._age # It's OK, although the IDE will show some warnings. (Access to a protected member _age of a class)
age2 = human.age # It's OK! see below:
"""
if you do not define `__getattribute__` at the class of Human,
the IDE will show you: Unresolved attribute reference 'age' for class 'Human'
but it's ok on running since the MetaMemberControl will help you.
"""
if __name__ == '__main__':
test_demo()
该metaclass
是强大的,有很多事情(如猴子魔法)你可以用它做,但要小心这可能只为你所知。
在面向对象编程中,元类是一个实例为类的类。 正如普通类定义某些对象的行为一样,元类定义某些类及其实例的行为 术语元类只是指用于创建类的东西。 换句话说,它是一个类的类。 元类用于创建类,就像对象是类的实例一样,类是元类的实例。 在python中,类也被认为是对象。
在Python中,类是一个对象,就像任何其他对象一样,它是"something"的实例。 这个"东西"就是所谓的元类。 这个元类是一种特殊类型的类,它创建了其他类的对象。 因此,元类负责创建新的类。 这允许程序员自定义类的生成方式。
要创建元类,通常会重写new()和init()方法。 new()可以被复盖以改变对象的创建方式,而init()可以被复盖以改变初始化对象的方式。 元类可以通过多种方式创建。 其中一种方法是使用type()函数。 type()函数,当用3个参数调用时,创建一个元类。 参数为:-
- 类名
- 具有由类继承的基类的元组
- 包含所有类方法和类变量的字典
创建元类的另一种方法包括'元类'关键字。 将元类定义为简单类。 在继承类的参数中,传递metaclass=metaclass_name
元类可以具体用于以下情况 :-
- 当必须对所有子类应用特定效果时
- 需要自动更改类(创建时)
- API开发人员
顶部答案是正确的。
但是读者可能会来这里寻找关于类似命名的内部类的答案。 它们存在于流行的库中,例如Django
和WTForms
。
正如DavidW在这个答案下面的评论中指出的那样,这些是库特定的功能,不要与具有类似名称的高级,不相关的Python语言功能混淆。
相反,这些是类dicts中的命名空间。 它们是为了可读性而使用内部类构造的。
在本例特殊字段中,abstract
与作者模型的字段明显分开。
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
class Meta:
abstract = True
另一个例子来自WTForms
的文档:
from wtforms.form import Form
from wtforms.csrf.session import SessionCSRF
from wtforms.fields import StringField
class MyBaseForm(Form):
class Meta:
csrf = True
csrf_class = SessionCSRF
name = StringField("name")
这种语法在python编程语言中没有得到特殊处理。 Meta
在这里不是关键字,并且不会触发元类行为。 相反,像Django
和WTForms
这样的包中的第三方库代码在某些类的构造函数和其他地方读取此属性。
这些声明的存在会修改具有这些声明的类的行为。 例如,WTForms
读取self.Meta.csrf
以确定表单是否需要csrf
字段。
在Python中,元类是子类的子类,它决定子类的行为方式。 类是另一个元类的实例。 在Python中,类指定类的实例的行为方式。
由于元类负责类生成,因此您可以编写自己的自定义元类,通过执行其他操作或注入代码来更改类的创建方式。 自定义元类并不总是重要的,但它们可以。
我在一个名为classutilities
的包中看到了元类的一个有趣的用例。 它检查所有的类变量是否都是大写格式(配置类有统一的逻辑很方便),并检查类中是否没有实例级别的方法。
Metaclases的另一个有趣的例子是基于复杂条件(检查多个环境变量的值)停用unittests。
什么是元编程?
简而言之,我们可以说元编程是操纵代码的代码。 Python支持一种称为元类的类元编程形式。
何时使用:
它通常用于一些复杂的东西,但是我们使用元类的一些情况是 –
- 元类向下传播继承层次结构。 它也会影响所有的子类。 如果我们有这样的情况,那么我们应该使用元类。
- 如果我们想自动更改类,当它被创建时,我们使用元类。
- 对于API开发,我们可能会使用元类。
- 此外,在创建时:日志记录和分析,接口检查,在创建时注册类,自动添加新方法 自动属性创建,代理,自动资源,锁定/同步。
新手图: <img alt="元类"src="https://i.stack.imgur.com/FOyn1.png缧/>
类工厂:
元类主要用作类工厂。 当您通过调用类来创建对象时,Python通过调用元类来创建一个新类。
>结合普通的__init__
和__new__
方法,元类,允许你在创建一个类时做额外的事情,比如用一些注册表注册新类或用别的东西完全替换类。
1-__new__():
这是一个在__init__()
之前调用的方法。 它创建对象并返回它。 我们可以重写这个方法来控制对象的创建方式。
2-__init__():
此方法只是初始化作为参数传递的创建对象。
定义元类的方法:
1-方法1:
class MyMeta1(type):
def __new__(cls, name, bases, dict):
pass
2-方法2:
class MyMeta2(type):
def __init__(self, name, bases, dict):
pass
看这个:
Python 3.10.0rc2 (tags/v3.10.0rc2:839d789, Sep 7 2021, 18:51:45) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Object:
... pass
...
>>> class Meta(type):
... test = 'Worked!!!'
... def __repr__(self):
... return 'This is "Meta" metaclass'
...
>>> class ObjectWithMetaClass(metaclass=Meta):
... pass
...
>>> Object or type(Object())
<class '__main__.Object'>
>>> ObjectWithMetaClass or type(ObjectWithMetaClass())
This is "Meta" metaclass
>>> Object.test
AttributeError: ...
>>> ObjectWithMetaClass.test
'Worked!!!'
>>> type(Object)
<class 'type'>
>>> type(ObjectWithMetaClass)
<class '__main__.Meta'>
>>> type(type(ObjectWithMetaClass))
<class 'type'>
>>> Object.__bases__
(<class 'object'>,)
>>> ObjectWithMetaClass.__bases__
(<class 'object'>,)
>>> type(ObjectWithMetaClass).__bases__
(<class 'type'>,)
>>> Object.__mro__
(<class '__main__.Object'>, <class 'object'>)
>>> ObjectWithMetaClass.__mro__
(This is "Meta" metaclass, <class 'object'>)
>>>
换句话说,当一个对象没有被创建(对象的类型)时,我们寻找元类。
元类是类的类。 类定义类的实例(即对象)的行为方式,而元类定义类的行为方式。 类是元类的实例。
虽然在Python中,您可以为元类使用任意可调用(如 Jerub 所示),但更好的方法是使其成为实际的类本身。
类型
是Python中常见的元类。类型
本身就是一个类,它是自己的类型。 你将无法纯粹在Python中重新创建类似type
的东西,但是Python有点作弊。 要在Python中创建自己的元类,你真的只想子类type
。元类最常用作类工厂。 当您通过调用类来创建对象时,Python通过调用元类来创建一个新类(当它执行'class'语句时)。 因此,结合普通的
__init__
和__new__
方法,元类允许您在创建类时做"额外的事情",比如用一些注册表注册新类或用其他东西完全替换类。当
class
语句执行时,Python首先将class
语句的主体作为普通代码块执行。 生成的命名空间(dict)保存类的属性。 元类是通过查看类的基类(元类是继承的)、类的__metaclass__
属性(如果有的话)或全局变量来确定的。 然后使用类的名称、基和属性调用元类以实例化它。但是,元类实际上定义了类的 类型 ,而不仅仅是它的工厂,所以你可以用它们做更多的事情。 例如,您可以在元类上定义普通方法。 这些元类方法就像classmethods,因为它们可以在没有实例的情况下在类上调用,但它们也不像classmethods,因为它们不能在类的实例上调用。
type.__subclasses__()
是type
元类上的方法示例。 您还可以定义正常的"魔术"方法,如__add__
,__iter__
和__getattr__
,以实现或更改类的行为方式。下面是一个点和点的聚合示例: