除了已发布的答案,我可以说 metaclass 定义了一个类的行为 . 因此,您可以明确设置您的元类 . 每当Python获得关键字 class 时,它就会开始搜索 metaclass . 如果是's not found – the default metaclass type is used to create the class'的对象 . 使用 __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'
5969
元类是类的类 . 就像类定义了类的实例的行为一样,元类定义了类的行为方式 . 类是元类的实例 .
虽然在Python中你可以为元类使用任意的callables(比如Jerub shows),但实际上更有用的方法是使它成为一个真正的类本身 . type 是Python中常用的元类 . 如果你想知道,是的, type 本身就是一个类,它是它自己的类型 . 你将无法在Python中重新创建像 type 这样的东西,但是Python会有所作为 . 要在Python中创建自己的元类,你真的只想继承 type .
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__
27
什么是元类?你用它们做什么的?
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
假设您需要一些简单的验证代码来运行您的属性 - 比如它必须始终是 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')
Note :这个例子很简单,它也可以用类装饰器完成,但可能是一个实际的元类会做得更多 .
'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
#!/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()
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
class type(object)
| type(object) -> the object's type
| type(name, bases, dict) -> a new type
元类需要3个参数 . ' name ', ' bases ' and ' 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
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
2248
tl; dr版本
type(obj) 函数可以获取对象的类型 .
The type() of a class is its metaclass.
要使用元类:
class Foo(object):
__metaclass__ = MyMetaClass
4
创建类实例时元类'__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__() magic方法时,后者是可能的 .
class SomeClass(object):
# ...
# some definition here ...
# ...
def __call__(self, foo, bar):
return bar + foo
当一个类的实例用作可调用对象时,将调用 __call__() 方法 . 但是当我们've seen from previous answers a class itself is an instance of a metaclass, so when we use the class as a callable (i.e. when we create an instance of it) we'实际上调用它的元类' __call__() 方法时 . 在这一点上,大多数Python程序员都有点困惑,因为他们被告知在创建像这样的实例 instance = SomeClass() 时,你正在调用它的 __init__() 方法 . 一些挖得更深的人知道在 __init__() 之前有 __new__() . 好吧,今天,在 __new__() 之前,正在揭示另一层真相.77539_ __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.
观察上面的代码没有实现,从而保持默认行为 . 由于 type 是 Meta_1 的父类( type 是默认的父元类)并且考虑到上面输出的排序顺序,我们现在有一个关于 type.__call__() 的伪实现的线索:
class type:
def __call__(cls, *args, **kwarg):
# ... maybe a few things done to cls here
# then we call __new__() on the class to create an instance
instance = cls.__new__(cls, *args, **kwargs)
# ... maybe a few things done to the instance here
# then we initialize the instance with its __init__() method
instance.__init__(*args, **kwargs)
# ... maybe a few more things done to instance here
# then we return it
return instance
我们可以看到元类' __call__() 方法是's called first. It then delegates creation of the instance to the class'的 __new__() 方法和实例的 __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
>>> class ObjectCreator(object):
... pass
...
>>> my_object = ObjectCreator()
>>> print(my_object)
<__main__.ObjectCreator object at 0x8974f2c>
但是类比Python更多 . 类也是对象 .
是的,对象 .
只要使用关键字 class ,Python就会执行它并创建一个OBJECT . 指示
>>> class ObjectCreator(object):
... pass
...
在内存中创建一个名为“ObjectCreator”的对象 .
This object (the class) is itself capable of creating objects (the instances), and this is why it's a class .
但是,它仍然是一个对象,因此:
您可以将其分配给变量
你可以复制它
您可以为其添加属性
您可以将其作为函数参数传递
例如 . :
>>> 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(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>
# 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)
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)
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)
15 回答
除了已发布的答案,我可以说
metaclass
定义了一个类的行为 . 因此,您可以明确设置您的元类 . 每当Python获得关键字class
时,它就会开始搜索metaclass
. 如果是's not found – the default metaclass type is used to create the class'的对象 . 使用__metaclass__
属性,您可以设置类的metaclass
:它将产生如下输出:
当然,您可以创建自己的
metaclass
来定义使用您的类创建的任何类的行为 .为此,必须继承您的默认
metaclass
类型类,因为这是主metaclass
:输出将是:
元类是类的类 . 就像类定义了类的实例的行为一样,元类定义了类的行为方式 . 类是元类的实例 .
虽然在Python中你可以为元类使用任意的callables(比如Jerub shows),但实际上更有用的方法是使它成为一个真正的类本身 .
type
是Python中常用的元类 . 如果你想知道,是的,type
本身就是一个类,它是它自己的类型 . 你将无法在Python中重新创建像type
这样的东西,但是Python会有所作为 . 要在Python中创建自己的元类,你真的只想继承type
.元类最常用作类工厂 . 就像通过调用类来创建类的实例一样,Python通过调用元类创建了一个新类(当它执行'class'语句时) . 结合普通的
__init__
和__new__
方法,元类因此允许您在创建类时执行'extra things',例如使用某个注册表注册新类,或者甚至完全用其他类替换该类 .执行
class
语句时,Python首先将class
语句的主体作为正常的代码块执行 . 生成的命名空间(dict)保存了将要进行的类的属性 . 元类是通过在待定类(如果有)的__metaclass__
属性或__metaclass__
全局变量中查看要被定义的类的基类(元类是继承的)来确定的 . 然后使用类的名称,基数和属性调用元类来实例化它 .但是,元类实际上定义了类的类型,而不仅仅是它的工厂,所以你可以用它们做更多的事情 . 例如,您可以在元类上定义常规方法 . 这些元类方法就像类方法一样,因为它们可以在没有实例的类上调用,但它们也不像类方法,因为它们不能在类的实例上调用 .
type.__subclasses__()
是type
元类的方法示例 . 您还可以定义常规'magic'方法,如__add__
,__iter__
和__getattr__
,以实现或更改类的行为方式 .这是比特和碎片的汇总示例:
TLDR:元类实例化并定义类的行为,就像类实例化一样,并定义实例的行为 .
伪代码:
以上应该看起来很熟悉 . 好吧,
Class
来自哪里?它是元类(也是伪代码)的一个实例:在实际代码中,我们可以传递默认元类
type
,我们需要实例化一个类,然后我们得到一个类:换句话说
当我们实例化一个对象时,我们得到一个实例:
同样,当我们使用默认元类
type
显式定义一个类时,我们实例化它:当您编写类定义并且Python执行它时,它使用元类来实例化类对象(反过来,它将用于实例化该类的实例) .
就像我们可以使用类定义来改变自定义对象实例的行为方式一样,我们可以使用元类定义来改变类对象的行为方式 .
它们可以用于什么?来自docs:
尽管如此,除非绝对必要,否则通常鼓励用户避免使用元类 .
每次创建类时都使用元类:
当你编写类定义时,例如,像这样,
您实例化一个类对象 .
它与使用适当的参数函数调用
type
并将结果分配给该名称的变量相同:注意,有些东西会自动添加到
__dict__
,即命名空间:在两种情况下,我们创建的对象的元类都是
type
.(关于类
__dict__
:__module__
的内容的附注是因为类必须知道它们的定义位置,并且__dict__
和__weakref__
在那里因为我们没有定义__slots__
- 如果我们define slots我们将节省一点空间在实例中,我们可以通过排除它们来禁止__dict__
和__weakref__
. 例如:......但我离题了 . )
我们可以像任何其他类定义一样扩展类型:
这是类的默认
__repr__
:在编写Python对象时,我们默认可以做的最有 Value 的事情之一就是为它提供一个好的
__repr__
. 当我们调用help(repr)
时,我们知道对__repr__
有一个很好的测试,它也需要测试相等性 -obj == eval(repr(obj))
. 以下为类型类的类实例的__repr__
和__eq__
的简单实现为我们提供了可以改进类的默认__repr__
的演示:所以现在当我们用这个元类创建一个对象时,在命令行上回显的
__repr__
提供了比默认值更不丑的视觉:通过为类实例定义了一个很好的
__repr__
,我们可以更强大地调试代码 . 但是,使用eval(repr(Class))
进行进一步检查是不太可能的(因为函数从它们的默认值__repr__
中进行评估是不可能的) .预期用法:__prepare__命名空间
例如,如果我们想知道创建类的方法的顺序,我们可以提供一个有序的dict作为类的命名空间 . 我们会用
__prepare__
执行此操作returns the namespace dict for the class if it is implemented in Python 3:用法:
现在我们记录了这些方法(和其他类属性)的创建顺序:
注意,这个例子改编自documentation - 新的enum in the standard library这样做 .
所以我们所做的是通过创建一个类来实例化一个元类 . 我们也可以像对待任何其他类一样对待元类 . 它有一个方法解析顺序:
并且它具有大致正确的
repr
(除非我们能找到表示我们函数的方法,否则我们不能再评估它) .type
实际上是一个metaclass
- 一个创建另一个类的类 . 大多数metaclass
是type
的子类 .metaclass
接收new
类作为其第一个参数,并提供对类对象的访问,其详细信息如下所述:Note:
请注意,该类在任何时候都没有实例化;创建类的简单行为触发了
metaclass
的执行 .type()函数可以返回对象的类型或创建新类型,
例如,我们可以使用type()函数创建一个Hi类,而不需要使用这种方式使用类Hi(object):
除了使用type()动态创建类之外,您还可以控制类的创建行为并使用元类 .
根据Python对象模型,类是对象,因此该类必须是另一个特定类的实例 . 默认情况下,Python类是类型类的实例 . 也就是说,type是大多数内置类的元类和用户定义类的元类 .
当我们在元类中传递关键字参数时,Magic将生效,它表示Python解释器通过ListMetaclass创建CustomList . new (),此时,我们可以修改类定义,例如,添加一个新方法,然后返回修改后的定义 .
Python 3 update
(在这一点上)元类中有两个关键方法:
__prepare__
,和__new__
__prepare__
允许您提供在创建类时用作命名空间的自定义映射(例如OrderedDict
) . 您必须返回您选择的任何名称空间的实例 . 如果你没有实现__prepare__
,则使用正常dict
.__new__
负责最终课程的实际创建/修改 .一个简单的,无所事事的额外元类想要:
一个简单的例子:
假设您需要一些简单的验证代码来运行您的属性 - 比如它必须始终是
int
或str
. 没有元类,您的类看起来像:如您所见,您必须重复两次属性的名称 . 这使得拼写错误以及恼人的错误成为可能 .
一个简单的元类可以解决这个问题:
这就是元类的样子(不使用
__prepare__
,因为它不需要):示例运行:
生产环境 :
Note :这个例子很简单,它也可以用类装饰器完成,但可能是一个实际的元类会做得更多 .
'ValidateType'类供参考:
元类的一个用途是自动向实例添加新属性和方法 .
例如,如果你看Django models,他们的定义看起来有点令人困惑 . 看起来好像只是定义了类属性:
但是,在运行时,Person对象充满了各种有用的方法 . 请参阅source了解一些神奇的元素 .
元类是一个类,它告诉我们应该如何(某些)创建其他类 .
这是我看到元类作为我的问题的解决方案的情况:我有一个非常复杂的问题,可能已经以不同的方式解决了,但我选择使用元类来解决它 . 由于其复杂性,它是我编写的少数几个模块之一,其中模块中的注释超过了已编写的代码量 . 这里是...
其他人已经解释了元类如何工作以及它们如何适合Python类型系统 . 以下是它们可用于什么的示例 . 在我编写的测试框架中,我想跟踪定义类的顺序,以便稍后我可以按此顺序实例化它们 . 我发现使用元类这样做最容易 .
然后,任何属于
MyType
的子类的东西都会获得一个类属性_order
,它记录了类的定义顺序 .Python类本身就是它们的元类的对象 - 例如 - .
默认元类,在您将类确定为时应用:
元类用于将一些规则应用于整个类集 . 例如,假设您正在构建一个ORM来访问数据库,并且您希望每个表中的记录都是映射到该表的类(基于字段,业务规则等),可能使用元类例如,连接池逻辑,它由所有表的所有记录类共享 . 另一个用途是支持外键的逻辑,它涉及多类记录 .
当你定义元类时,你是子类类型,并且可以覆盖以下魔术方法来插入你的逻辑 .
无论如何,这两个是最常用的钩子 . 元类化是强大的,并且上面是远程接近和详尽的元类别用途列表 .
注意,这个答案适用于Python 2.x,因为它是在2008年编写的,元类在3.x中略有不同,请参阅注释 .
元类是使“阶级”工作的秘诀 . 新样式对象的默认元类称为“类型” .
元类需要3个参数 . ' name ', ' bases ' and ' dict '
这是秘密开始的地方 . 在此示例类定义中查找name,bases和dict的来源 .
让我们定义一个元类,它将演示' class: '如何调用它 .
现在,一个实际意味着什么的例子,这将自动使列表中的变量“属性”设置在类上,并设置为None .
请注意,'Initalised'通过使用元类
init_attributes
获得的魔术行为不会传递到Initalised的子类 .这是一个更具体的例子,展示了如何子类化'type'来创建一个在创建类时执行操作的元类 . 这非常棘手:
tl; dr版本
type(obj)
函数可以获取对象的类型 .The type() of a class is its metaclass.
要使用元类:
创建类实例时元类'__call __()方法的作用
如果你已经完成Python编程超过几个月,你最终会偶然发现如下所示的代码:
当您在类上实现
__call__()
magic方法时,后者是可能的 .当一个类的实例用作可调用对象时,将调用
__call__()
方法 . 但是当我们've seen from previous answers a class itself is an instance of a metaclass, so when we use the class as a callable (i.e. when we create an instance of it) we'实际上调用它的元类'__call__()
方法时 . 在这一点上,大多数Python程序员都有点困惑,因为他们被告知在创建像这样的实例instance = SomeClass()
时,你正在调用它的__init__()
方法 . 一些挖得更深的人知道在__init__()
之前有__new__()
. 好吧,今天,在__new__()
之前,正在揭示另一层真相.77539___call__()
.让我们从创建类实例的角度研究方法调用链 .
这是一个元类,它精确记录实例创建之前的时刻以及它将要返回的时刻 .
这是一个使用该元类的类
现在让我们创建一个
Class_1
的实例观察上面的代码没有实现,从而保持默认行为 . 由于
type
是Meta_1
的父类(type
是默认的父元类)并且考虑到上面输出的排序顺序,我们现在有一个关于type.__call__()
的伪实现的线索:我们可以看到元类'
__call__()
方法是's called first. It then delegates creation of the instance to the class'的__new__()
方法和实例的__init__()
初始化方法 . 它也是最终返回实例的那个 .从上面可以看出,元类'
__call__()
也有机会决定是否最终调用Class_1.__new__()
或Class_1.__init__()
. 在执行过程中,它实际上可以返回一个未被这些方法触及的对象 . 以单例模式的这种方法为例:让我们观察一下当重复尝试创建
Class_2
类型的对象时会发生什么作为对象的类
在理解元类之前,您需要掌握Python中的类 . Python对Smalltalk语言借用的类有一个非常奇特的想法 .
在大多数语言中,类只是描述如何生成对象的代码片段 . 在Python中也是如此:
但是类比Python更多 . 类也是对象 .
是的,对象 .
只要使用关键字
class
,Python就会执行它并创建一个OBJECT . 指示在内存中创建一个名为“ObjectCreator”的对象 .
This object (the class) is itself capable of creating objects (the instances), and this is why it's a class .
但是,它仍然是一个对象,因此:
您可以将其分配给变量
你可以复制它
您可以为其添加属性
您可以将其作为函数参数传递
例如 . :
动态创建类
由于类是对象,因此您可以像任何对象一样动态创建它们 .
首先,您可以使用
class
在函数中创建一个类:但它不是那么有活力,因为你还是要自己写全班 .
由于类是对象,因此它们必须由某些东西生成 .
使用
class
关键字时,Python会自动创建此对象 . 但与Python中的大多数内容一样,它为您提供了一种手动操作方法 .还记得函数
type
吗?一个很好的旧函数,可以让您知道对象的类型:好吧,type具有完全不同的能力,它也可以动态创建类 .
type
可以将类的描述作为参数,并返回一个类 .(我知道,根据您传递给它的参数,同一个函数可以有两个完全不同的用途,这很愚蠢 . 由于Python的向后兼容性,这是一个问题)
type
以这种方式工作:例如 . :
可以通过以下方式手动创建:
您会注意到我们使用“MyShinyClass”作为类的名称,并使用变量来保存类引用 . 它们可以不同,但没有理由使事情复杂化 .
type
接受字典来定义类的属性 . 所以:可以翻译成:
并用作普通类:
当然,你可以继承它,所以:
将会:
最后,您需要为您的 class 添加方法 . 只需使用正确的签名定义一个函数并将其指定为属性即可 .
在动态创建类之后,您可以添加更多方法,就像向正常创建的类对象添加方法一样 .
你会看到我们要去的地方:在Python中,类是对象,你可以动态地创建一个类 .
这是Python在使用关键字_77350时所执行的操作,它通过使用元类来实现 .
什么是元类(最后)
元类是创建类的“东西” .
你定义类来创建对象,对吗?
但我们了解到Python类是对象 .
好吧,元类是创建这些对象的原因 . 他们是 class 的 class ,你可以这样画出来:
您已经看到
type
允许您执行以下操作:这是因为函数
type
实际上是一个元类 .type
是Python用于在幕后创建所有类的元类 .现在你想知道为什么它是用小写写的,而不是
Type
?好吧,我想这是与
str
(创建字符串对象的类)和int
(创建整数对象的类)的一致性问题 .type
只是创建类对象的类 .您可以通过检查
__class__
属性来查看 .一切,我的意思是一切,都是Python中的一个对象 . 这包括整数,字符串,函数和类 . 所有这些都是对象 . 所有这些都是从一个类创建的:
现在,任何
__class__
的__class__
是什么?因此,元类只是创建类对象的东西 .
如果您愿意,可以称之为“ class 工厂” .
type
是Python使用的内置元类,但当然,您可以创建自己的元类 .__metaclass__属性
在Python 2中,您可以在编写类时添加
__metaclass__
属性(请参阅Python 3语法的下一节):如果这样做,Python将使用元类创建类
Foo
.小心,这很棘手 .
首先编写
class Foo(object)
,但类对象Foo
尚未在内存中创建 .Python将在类定义中查找
__metaclass__
. 如果找到它,它将使用它来创建对象类Foo
. 如果没有,它将使用type
来创建类 .读那个几次 .
当你这样做时:
Python执行以下操作:
Foo
中是否有__metaclass__
属性?如果是的话,在内存中创建一个类对象(我说一个类对象,请留在这里),名称为
Foo
,使用__metaclass__
中的内容 .如果Python找不到
__metaclass__
,它将在MODULE级别查找__metaclass__
,并尝试执行相同的操作(但仅适用于不继承任何内容的类,基本上是旧式类) .然后,如果它根本找不到任何
__metaclass__
,它将使用Bar
(第一个父)自己的元类(可能是默认的type
)来创建类对象 .这里要小心,不会继承
__metaclass__
属性,父类的元类(Bar.__class__
)将是 . 如果Bar
使用__metaclass__
属性创建Bar
与type()
(而不是type.__new__()
),则子类将不会继承该行为 .现在最大的问题是,你能把什么放进
__metaclass__
?答案是:可以创建一个类的东西 .
什么可以创造一个类?
type
,或任何子类或使用它的东西 .Python中的元类3
在Python 3中更改了设置元类的语法:
即不再使用
__metaclass__
属性,而是支持基类列表中的关键字参数 .然而,元类的行为仍然是largely the same .
自定义元类
元类的主要目的是在创建类时自动更改类 .
您通常对API执行此操作,您希望在其中创建与当前上下文匹配的类 .
想象一个愚蠢的例子,你决定模块中的所有类都应该用大写字母写出它们的属性 . 有几种方法可以做到这一点,但一种方法是在模块级别设置
__metaclass__
.这样,将使用此元类创建此模块的所有类,我们只需告诉元类将所有属性转换为大写 .
幸运的是,
__metaclass__
实际上可以是任何可调用的,它不需要成为一个类,去图......但它很有帮助) .因此,我们将从一个简单的例子开始,使用一个函数 .
现在,让我们做同样的事情,但是使用真正的类来表示元类:
但这不是真正的OOP . 我们直接调用
type
,我们不会覆盖或调用父__new__
. 我们开始做吧:你可能已经注意到额外的参数
upperattr_metaclass
. 它没有什么特别之处:__new__
总是接收它定义的类,作为第一个参数 . 就像你有self
用于接收实例作为第一个参数的普通方法,或者类方法的定义类 .当然,为了清楚起见,我在这里使用的名称很长,但是对于
self
,所有参数都有常规名称 . 所以真正的 生产环境 元类看起来像这样:我们可以通过使用_77410来使它更干净,这将简化继承(因为是的,你可以有元类,继承自元类,继承自类型):
而已 . 实际上没有关于元类的更多信息 .
使用元类的代码复杂性背后的原因不是因为元类,而是因为你通常使用元类来依赖于内省,操纵继承,诸如
__dict__
之类的变量等来做扭曲的东西 .实际上,元类特别适用于制作黑魔法,因此也很复杂 . 但它们本身很简单:
拦截一个类创建
修改类
返回修改后的类
为什么要使用元类而不是函数?
由于
__metaclass__
可以接受任何可调用的,为什么你会使用一个类,因为它显然更复杂?有几个原因可以这样做:
意图很清楚 . 当你阅读
UpperAttrMetaclass(type)
时,你知道会发生什么您可以使用OOP . Metaclass可以从元类继承,覆盖父方法 . 元类甚至可以使用元类 .
如果指定了元类,但没有使用元类函数,则类的子类将是其元类的实例 .
您可以更好地构建代码 . 你从不使用元类来处理像上面例子那样简单的事情 . 它通常用于复杂的事情 . 能够制作多个方法并将它们组合在一个类中对于使代码更易于阅读非常有用 .
您可以挂钩
__new__
,__init__
和__call__
. 这将允许你做不同的东西 . 即使通常你可以在__new__
中完成所有工作,但有些人使用__init__
会更舒服 .这些被称为元类,该死的!它必须意味着什么!
为什么要使用元类?
现在是个大问题 . 为什么要使用一些不起眼的容易出错的功能?
好吧,通常你不会:
Python大师Tim Peters
元类的主要用例是创建API . 一个典型的例子是Django ORM .
它允许您定义如下内容:
但是如果你这样做:
它不会返回
IntegerField
对象 . 它将返回int
,甚至可以直接从数据库中获取它 .这是可能的,因为
models.Model
定义了__metaclass__
并且它使用了一些魔法,它将您刚刚使用简单语句定义的Person
转换为数据库字段的复杂挂钩 .Django通过公开一个简单的API并使用元类,从这个API重新创建代码来完成幕后的实际工作,从而使复杂的外观变得简单 .
最后一个字
首先,您知道类是可以创建实例的对象 .
事实上,类本身就是实例 . 元类 .
一切都是Python中的对象,它们都是类的实例或元类的实例 .
type
除外 .type
实际上是它自己的元类 . 这不是你可以在纯Python中重现的东西,而是通过在实现级别上作弊来完成的 .其次,元类很复杂 . 您可能不希望将它们用于非常简单的类更改 . 您可以使用两种不同的技术更改类:
monkey patching
类装饰器
99%的时间你需要改变课程,你最好使用这些 .
但是98%的情况下,你根本不需要改变课程 .
我认为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类中也需要是第一类对象来启用此行为 .
我自己从未写过,但我认为在_77452中可以看到元类最好的用法之一 . 模型类使用元类方法来启用编写新模型或表单类的声明式样式 . 当元类创建类时,所有成员都可以自定义类 .
Creating a new model
The metaclass enabling this
's left to say is: If you don'知道什么是元类的东西,你 will not need them 的概率是99% .