Python中的元类是什么?

元类是什么,我们将它们用于什么?


#1楼

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

元类是使“类”工作的秘诀。 新样式对象的默认元类称为“类型”。

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

元类带有3个参数。 ' 名称 ',' 基数 '和' 字典 '

这是秘密的开始。 在此示例类定义中查找名称,基数和字典来自何处。

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

让我们定义一个元类,该元类将演示“ 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'

现在,一个实际上意味着含义的示例将自动使列表中的变量“设置为”类,并设置为“无”。

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

请注意,通过具有元类init_attributes获得Initialised的魔术行为不会传递给Initialised的子类。

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

class MetaSingleton(type):
    instance = None
    def __call__(cls, *args, **kw):
        if cls.instance is None:
            cls.instance = super(MetaSingleton, cls).__call__(*args, **kw)
        return cls.instance

class Foo(object):
    __metaclass__ = MetaSingleton

a = Foo()
b = Foo()
assert a is b

#2楼

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


#3楼

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

例如,如果您查看Django模型 ,则其定义看起来有些混乱。 似乎您只是在定义类属性:

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

但是,在运行时,Person对象充满了各种有用的方法。 请参阅源代码中一些惊人的元类。


#4楼

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

尽管在Python中您可以对元类使用任意可调用对象(例如Jerub演示),但更好的方法是使其成为实际的类。 type是Python中常见的元类。 type本身是一个类,并且是它自己的类型。 您将无法纯粹在Python中重新创建类似type ,但是Python会有些作弊。 要在Python中创建自己的元类,您实际上只想对type进行子type

元类最常用作类工厂。 当通过调用类创建对象时,Python通过调用元类来创建一个新类(当执行“ class”语句时)。 因此,与常规的__init____new__方法结合使用,元类允许您在创建类时执行“其他操作”,例如使用某些注册表注册新类或将其完全替换为其他类。

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

但是,元类实际上定义了类的类型 ,而不仅仅是它的工厂,因此您可以使用它们做更多的事情。 例如,您可以在元类上定义常规方法。 这些元类方法就像类方法,因为它们可以在没有实例的情况下在类上调用,但是它们也不像类方法,因为它们不能在类的实例上被调用。 type.__subclasses__()type元类上方法的示例。 您还可以定义常规的“魔术”方法,例如__add__ __iter____getattr__ __add____getattr__ ,以实现或更改类的行为。

这是点滴的汇总示例:

def make_hook(f):
    """Decorator to turn 'foo' method into '__foo__'"""
    f.is_hook = 1
    return f

class MyType(type):
    def __new__(mcls, name, bases, attrs):

        if name.startswith('None'):
            return None

        # Go over attributes and see if they should be renamed.
        newattrs = {}
        for attrname, attrvalue in attrs.iteritems():
            if getattr(attrvalue, 'is_hook', 0):
                newattrs['__%s__' % attrname] = attrvalue
            else:
                newattrs[attrname] = attrvalue

        return super(MyType, mcls).__new__(mcls, name, bases, newattrs)

    def __init__(self, name, bases, attrs):
        super(MyType, self).__init__(name, bases, attrs)

        # classregistry.register(self, self.interfaces)
        print "Would register class %s now." % self

    def __add__(self, other):
        class AutoClass(self, other):
            pass
        return AutoClass
        # Alternatively, to autogenerate the classname as well as the class:
        # return type(self.__name__ + other.__name__, (self, other), {})

    def unregister(self):
        # classregistry.unregister(self)
        print "Would unregister class %s now." % self

class MyObject:
    __metaclass__ = MyType


class NoneSample(MyObject):
    pass

# Will print "NoneType None"
print type(NoneSample), repr(NoneSample)

class Example(MyObject):
    def __init__(self, value):
        self.value = value
    @make_hook
    def add(self, other):
        return self.__class__(self.value + other.value)

# Will unregister the class
Example.unregister()

inst = Example(10)
# Will fail with an AttributeError
#inst.unregister()

print inst + inst
class Sibling(MyObject):
    pass

ExampleSibling = Example + Sibling
# ExampleSibling is now a subclass of both Example and Sibling (with no
# content of its own) although it will believe it's called 'AutoClass'
print ExampleSibling
print ExampleSibling.__mro__

#5楼

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

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

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

#6楼

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

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

当您编写一个类定义并执行它时,Python使用一个元类来实例化该类对象(而该对象又将用于实例化该类的实例)。

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

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

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

但是,通常鼓励用户避免使用元类,除非绝对必要。

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

例如,当您编写类定义时,

class Foo(object): 
    'demo'

您实例化一个类对象。

>>> Foo
<class '__main__.Foo'>
>>> isinstance(Foo, type), isinstance(Foo, object)
(True, True)

它与带有适当参数的函数调用type相同,并将结果分配给该名称的变量相同:

name = 'Foo'
bases = (object,)
namespace = {'__doc__': 'demo'}
Foo = type(name, bases, namespace)

注意,一些东西会自动添加到__dict__ ,即名称空间:

>>> Foo.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'Foo' objects>, 
'__module__': '__main__', '__weakref__': <attribute '__weakref__' 
of 'Foo' objects>, '__doc__': 'demo'})

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

在类的内容(A侧面说明__dict____module__是有,因为类必须知道它们被定义在哪里,以及__dict____weakref__在那里,因为我们没有定义__slots__ -如果我们定义__slots__我们会节省一点实例中的空格,因为我们可以通过排除__dict____weakref__来禁止它们,例如:

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

...但是我离题了。)

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

这是默认的__repr__类:

>>> Foo
<class '__main__.Foo'>

默认情况下,我们在编写Python对象时可以做的最有价值的事情之一就是为其提供良好的__repr__ 。 当我们调用help(repr)我们了解到__repr__有一个很好的测试,它也需要测试相等性__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__ ,我们可以更强__repr__调试我们的代码。 但是,使用eval(repr(Class))进一步检查的可能性不大(因为从其默认__repr__进行评估的功能相当不可能)。

预期的用法: __prepare__名称空间

例如,如果我们想知道创建类方法的顺序,可以提供一个有序的dict作为类的名称空间。 我们将使用__prepare__进行此操作, 如果该类是在Python 3中实现的,它将返回该类的名称空间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>})

#7楼

Python 3更新

(在这一点上)元类中有两个关键方法:

  • __prepare__ ,以及
  • __new__

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

__new__负责最终课程的实际创建/修改。

一个简单的,不做任何事情的超类将是:

class Meta(type):

    def __prepare__(metaclass, cls, bases):
        return dict()

    def __new__(metacls, cls, bases, clsdict):
        return super().__new__(metacls, cls, bases, clsdict)

一个简单的例子:

假设您要在属性上运行一些简单的验证代码-就像它必须始终是intstr 。 没有元类,您的类将类似于:

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

#8楼

type实际上是一个metaclass -创建另一个类的类。 大多数metaclass类是type的子typemetaclassnew类作为其第一个参数,并提供对类对象的访问,其细节如下所述:

>>> 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执行。


#9楼

创建类实例时元类的__call__()方法的作用

如果您已经完成Python编程超过几个月,那么您最终会发现以下代码:

# define a class
class SomeClass(object):
    # ...
    # some definition here ...
    # ...

# create an instance of it
instance = SomeClass()

# then call the object as if it's a function
result = instance('foo', 'bar')

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

class SomeClass(object):
    # ...
    # some definition here ...
    # ...

    def __call__(self, foo, bar):
        return bar + foo

当类的实例用作可调用对象时,将调用__call__()方法。 但是,正如我们从前面的答案中看到的那样,类本身是元类的实例,因此,当我们使用该类作为可调用对象时(即,当我们创建它的实例时),实际上是在调用其元类的__call__()方法。 在这一点上,大多数Python程序员有些困惑,因为他们被告知在创建类似instance = SomeClass()您正在调用其__init__()方法。 一些更深入的研究知道__init__()之前有__new__() 。 好吧,今天又有了另一层真相,在__new__()之前是元类的__call__()

让我们从创建类实例的角度专门研究方法调用链。

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

class Meta_1(type):
    def __call__(cls):
        print "Meta_1.__call__() before creating an instance of ", cls
        instance = super(Meta_1, cls).__call__()
        print "Meta_1.__call__() about to return instance."
        return instance

这是使用该元类的类

class Class_1(object):

    __metaclass__ = Meta_1

    def __new__(cls):
        print "Class_1.__new__() before creating an instance."
        instance = super(Class_1, cls).__new__(cls)
        print "Class_1.__new__() about to return instance."
        return instance

    def __init__(self):
        print "entering Class_1.__init__() for instance initialization."
        super(Class_1,self).__init__()
        print "exiting Class_1.__init__()."

现在让我们创建Class_1的实例

instance = Class_1()
# Meta_1.__call__() before creating an instance of <class '__main__.Class_1'>.
# Class_1.__new__() before creating an instance.
# Class_1.__new__() about to return instance.
# entering Class_1.__init__() for instance initialization.
# exiting Class_1.__init__().
# Meta_1.__call__() about to return instance.

请注意,上面的代码除了记录任务之外实际上没有做任何其他事情。 每个方法将实际工作委托给其父级的实现,从而保留默认行为。 由于typeMeta_1的父类( type是默认的父元类),并考虑了上面输出的排序顺序,因此我们现在可以知道type.__call__()的伪实现是什么:

class type:
    def __call__(cls, *args, **kwarg):

        # ... maybe a few things done to cls here

        # then we call __new__() on the class to create an instance
        instance = cls.__new__(cls, *args, **kwargs)

        # ... maybe a few things done to the instance here

        # then we initialize the instance with its __init__() method
        instance.__init__(*args, **kwargs)

        # ... maybe a few more things done to instance here

        # then we return it
        return instance

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

从上面可以得出,元类的__call__()也有机会决定是否最终对Class_1.__new__()Class_1.__init__()进行调用。 在执行过程中,它实际上可能返回这两个方法都未触及的对象。 以这种单例模式的方法为例:

class Meta_2(type):
    singletons = {}

    def __call__(cls, *args, **kwargs):
        if cls in Meta_2.singletons:
            # we return the only instance and skip a call to __new__()
            # and __init__()
            print ("{} singleton returning from Meta_2.__call__(), "
                   "skipping creation of new instance.".format(cls))
            return Meta_2.singletons[cls]

        # else if the singleton isn't present we proceed as usual
        print "Meta_2.__call__() before creating an instance."
        instance = super(Meta_2, cls).__call__(*args, **kwargs)
        Meta_2.singletons[cls] = instance
        print "Meta_2.__call__() returning new instance."
        return instance

class Class_2(object):

    __metaclass__ = Meta_2

    def __new__(cls, *args, **kwargs):
        print "Class_2.__new__() before creating instance."
        instance = super(Class_2, cls).__new__(cls)
        print "Class_2.__new__() returning instance."
        return instance

    def __init__(self, *args, **kwargs):
        print "entering Class_2.__init__() for initialization."
        super(Class_2, self).__init__()
        print "exiting Class_2.__init__()."

让我们观察一下,反复尝试创建Class_2类型的对象时会发生什么

a = Class_2()
# Meta_2.__call__() before creating an instance.
# Class_2.__new__() before creating instance.
# Class_2.__new__() returning instance.
# entering Class_2.__init__() for initialization.
# exiting Class_2.__init__().
# Meta_2.__call__() returning new instance.

b = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.

c = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.

a is b is c # True

#10楼

tl; dr版本

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

类的type()是其元类

要使用元类:

class Foo(object):
    __metaclass__ = MyMetaClass

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


#11楼

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

无论如何,这两个是最常用的钩子。 元分类功能强大,而元数据分类的用途清单也不是详尽无遗。


#12楼

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

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

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

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

type(Hi)
type

type(h)
__main__.Hi

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

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

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

class CustomList(list, metaclass=ListMetaclass):
    pass

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

lst
['custom_list_1', 'custom_list_2']

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


#13楼

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

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

print(MyClass.__metaclass__)

它将产生如下输出:

class 'type'

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

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

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

class MyTestClass:
   __metaclass__ = MyMetaClass

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

输出将是:

class '__main__.MyMetaClass'
class 'type'

#14楼

在面向对象的编程中,元类是一个类,其实例是类。 正如普通类定义某些对象的行为一样,元类定义某些类及其实例的行为。术语“元类”仅表示用于创建类的内容。 换句话说,它是一个类的类。 元类用于创建类,因此就像对象是类的实例一样,类是元类的实例。 在python中,类也被视为对象。


#15楼

其他人则解释了元类如何工作以及它们如何适合Python类型系统。 这是它们可以用来做什么的一个例子。 在我编写的测试框架中,我想跟踪定义类的顺序,以便以后可以按此顺序实例化它们。 我发现使用元类执行此操作最简单。

class MyMeta(type):

    counter = 0

    def __init__(cls, name, bases, dic):
        type.__init__(cls, name, bases, dic)
        cls._order = MyMeta.counter
        MyMeta.counter += 1

class MyType(object):              # Python 2
    __metaclass__ = MyMeta

class MyType(metaclass=MyMeta):    # Python 3
    pass

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


#16楼

类作为对象

在理解元类之前,您需要掌握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在函数中创建一个class

>>> def choose_class(name):
...     if name == 'foo':
...         class Foo(object):
...             pass
...         return Foo # return the class, not an instance
...     else:
...         class Bar(object):
...             pass
...         return Bar
...
>>> MyClass = choose_class('foo')
>>> print(MyClass) # the function returns a class, not an instance
<class '__main__.Foo'>
>>> print(MyClass()) # you can create an object from this class
<__main__.Foo object at 0x89c6d4c>

但这并不是那么动态,因为您仍然必须自己编写整个类。

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

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

还记得函数type吗? 好的旧函数可以让您知道对象的类型:

>>> print(type(1))
<type 'int'>
>>> print(type("1"))
<type 'str'>
>>> print(type(ObjectCreator))
<type 'type'>
>>> print(type(ObjectCreator()))
<class '__main__.ObjectCreator'>

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

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

type这种方式工作:

type(name of the class,
     tuple of the parent class (for inheritance, can be empty),
     dictionary containing attributes names and values)

例如:

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

可以通过以下方式手动创建:

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

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

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

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

可以翻译为:

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

并用作普通类:

>>> print(Foo)
<class '__main__.Foo'>
>>> print(Foo.bar)
True
>>> f = Foo()
>>> print(f)
<__main__.Foo object at 0x8a9b84c>
>>> print(f.bar)
True

当然,您可以从中继承,因此:

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

将会:

>>> FooChild = type('FooChild', (Foo,), {})
>>> print(FooChild)
<class '__main__.FooChild'>
>>> print(FooChild.bar) # bar is inherited from Foo
True

最终,您需要向类中添加方法。 只需定义具有适当签名的函数并将其分配为属性即可。

>>> def echo_bar(self):
...       print(self.bar)
...
>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})
>>> hasattr(Foo, 'echo_bar')
False
>>> hasattr(FooChild, 'echo_bar')
True
>>> my_foo = FooChild()
>>> my_foo.echo_bar()
True

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

>>> def echo_bar_more(self):
...       print('yet another method')
...
>>> FooChild.echo_bar_more = echo_bar_more
>>> hasattr(FooChild, 'echo_bar_more')
True

您会看到我们要去的方向:在Python中,类是对象,您可以动态地动态创建类。

这是Python在使用关键字class时所做的,并且通过使用元类来实现。

什么是元类(最终)

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

您定义类是为了创建对象,对吗?

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

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

MyClass = MetaClass()
my_object = MyClass()

您已经看到该type可以执行以下操作:

MyClass = type('MyClass', (), {})

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

现在,您想知道为什么用小写而不是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__属性

在Python 2中,您可以在编写类时添加__metaclass__属性(有关Python 3语法,请参见下一部分):

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

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

小心点,这很棘手。

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

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

读几次。

当您这样做时:

class Foo(Bar):
    pass

Python执行以下操作:

Foo__metaclass__属性吗?

如果是,请使用__metaclass__在内存中创建一个名称为Foo的类对象(我说一个类对象,在这里呆在一起)。

如果Python不能找到__metaclass__ ,它会寻找一个__metaclass__在模块级,并尝试做同样的(但仅适用于不继承任何东西,基本上都是老式类类)。

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

这里要小心,不要继承__metaclass__属性,父类的元类( Bar.__class__ )将被继承。 如果Bar使用__metaclass__属性创建了带有type() Bar (而不是type.__new__() ),则子类将不会继承该行为。

现在最大的问题是,您可以在__metaclass____metaclass__什么?

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

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

Python 3中的元类

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

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

也就是说,不再使用__metaclass__属性,而是在基类列表中使用关键字参数。

但是,元类的行为基本保持不变

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

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

阅读以下部分,了解python如何处理此问题。

自定义元类

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

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

想象一个愚蠢的示例,在该示例中,您决定模块中的所有类的属性都应以大写形式编写。 有多种方法可以执行此操作,但是一种方法是在模块级别设置__metaclass__

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

幸运的是, __metaclass__实际上可以是任何可调用的,它不必是正式的类(我知道,名称中带有“ class”的东西不必是一个类,如图……但这很有用)。

因此,我们将从使用一个简单示例开始,使用一个函数。

# the metaclass will automatically get passed the same argument
# that you usually pass to `type`
def upper_attr(future_class_name, future_class_parents, future_class_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)

但这不是真正的面向对象。 我们直接调用type ,而不覆盖或调用父级__new__ 。 我们开始做吧:

class UpperAttrMetaclass(type):

    def __new__(upperattr_metaclass, future_class_name,
                future_class_parents, future_class_attr):

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

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

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

当然,为了清楚起见,我在这里使用的名称很长,但是与self ,所有参数都具有常规名称。 因此,实际的生产元类将如下所示:

class UpperAttrMetaclass(type):

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

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

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

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

class UpperAttrMetaclass(type):

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

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

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

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

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

它将在元类中转换为使用它:

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

而已。 实际上,关于元类的更多信息了。

使用元类的代码复杂的背后原因不是因为元类,而是因为您通常使用元类依靠自省,操纵继承以及诸如__dict__ var等来扭曲事物。

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

  • 拦截课程创建
  • 修改班级
  • 返回修改后的类

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

由于__metaclass__可以接受任何可调用的对象,为什么要使用一个类,因为它显然更复杂?

这样做有几个原因:

  • 意图很明确。 当您阅读UpperAttrMetaclass(type) ,您知道会发生什么
  • 您可以使用OOP。 元类可以继承元类,重写父方法。 元类甚至可以使用元类。
  • 如果您指定了元类类,但没有元类函数,则该类的子类将是其元类的实例。
  • 您可以更好地构建代码。 绝对不要像上面的示例那样将元类用于琐碎的事情。 通常用于复杂的事情。 能够制作几种方法并将它们分组在一个类中的能力对于使代码更易于阅读非常有用。
  • 您可以挂接__new__ __init____init____call__ 。 这将使您可以做不同的事情。 即使通常您可以在__new__完成所有__new__ ,但有些人还是更习惯使用__init__
  • 这些被称为元类,该死! 它一定意味着什么!

为什么要使用元类?

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

好吧,通常您不会:

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

Python大师Tim Peters

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

它允许您定义如下内容:

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

但是,如果您这样做:

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

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

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

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

最后一个字

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

实际上,类本身就是实例。 元类的。

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

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

type除外。

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

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

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

但是在98%的时间中,您根本不需要更改班级。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值