是否可以链接元类?
我有一个Model
类,它使用__metaclass__=ModelBase
来处理它的命名空间dict。我将继承它并“绑定”另一个元类,因此它不会遮蔽原始元类。
第一种方法是继承class MyModelBase(ModelBase)
:
MyModel(Model):
__metaclass__ = MyModelBase # inherits from `ModelBase`
但是有没有可能只是像mixin一样链接它们而没有明确的子类化?像
这样的东西class MyModel(Model):
__metaclass__ = (MyMixin, super(Model).__metaclass__)
......甚至更好:创建一个MixIn,它将使用来自使用它的类的直接父级的__metaclass__
:
class MyModel(Model):
__metaclass__ = MyMetaMixin, # Automagically uses `Model.__metaclass__`
原因:为了更灵活地扩展现有应用程序,我想创建一个全局机制,用于挂钩Django中Model
,Form
,......定义的过程,以便可以更改在运行时。
一种常见的机制比使用回调mixin实现多个元类要好得多。
在你的帮助下,我终于找到了一个解决方案:元类MetaProxy
。
这个想法是:创建一个调用回调的元类来修改正在创建的类的名称空间,然后,在__new__
的帮助下,变异为其中一个父类的元类
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# Magical metaclass
class MetaProxy(type):
""" Decorate the class being created & preserve __metaclass__ of the parent
It executes two callbacks: before & after creation of a class,
that allows you to decorate them.
Between two callbacks, it tries to locate any `__metaclass__`
in the parents (sorted in MRO).
If found — with the help of `__new__` method it
mutates to the found base metaclass.
If not found — it just instantiates the given class.
"""
@classmethod
def pre_new(cls, name, bases, attrs):
""" Decorate a class before creation """
return (name, bases, attrs)
@classmethod
def post_new(cls, newclass):
""" Decorate a class after creation """
return newclass
@classmethod
def _mrobases(cls, bases):
""" Expand tuple of base-classes ``bases`` in MRO """
mrobases = []
for base in bases:
if base is not None: # We don't like `None` :)
mrobases.extend(base.mro())
return mrobases
@classmethod
def _find_parent_metaclass(cls, mrobases):
""" Find any __metaclass__ callable in ``mrobases`` """
for base in mrobases:
if hasattr(base, '__metaclass__'):
metacls = base.__metaclass__
if metacls and not issubclass(metacls, cls): # don't call self again
return metacls#(name, bases, attrs)
# Not found: use `type`
return lambda name,bases,attrs: type.__new__(type, name, bases, attrs)
def __new__(cls, name, bases, attrs):
mrobases = cls._mrobases(bases)
name, bases, attrs = cls.pre_new(name, bases, attrs) # Decorate, pre-creation
newclass = cls._find_parent_metaclass(mrobases)(name, bases, attrs)
return cls.post_new(newclass) # Decorate, post-creation
# Testing
if __name__ == '__main__':
# Original classes. We won't touch them
class ModelMeta(type):
def __new__(cls, name, bases, attrs):
attrs['parentmeta'] = name
return super(ModelMeta, cls).__new__(cls, name, bases, attrs)
class Model(object):
__metaclass__ = ModelMeta
# Try to subclass me but don't forget about `ModelMeta`
# Decorator metaclass
class MyMeta(MetaProxy):
""" Decorate a class
Being a subclass of `MetaProxyDecorator`,
it will call base metaclasses after decorating
"""
@classmethod
def pre_new(cls, name, bases, attrs):
""" Set `washere` to classname """
attrs['washere'] = name
return super(MyMeta, cls).pre_new(name, bases, attrs)
@classmethod
def post_new(cls, newclass):
""" Append '!' to `.washere` """
newclass.washere += '!'
return super(MyMeta, cls).post_new(newclass)
# Here goes the inheritance...
class MyModel(Model):
__metaclass__ = MyMeta
a=1
class MyNewModel(MyModel):
__metaclass__ = MyMeta # Still have to declare it: __metaclass__ do not inherit
a=2
class MyNewNewModel(MyNewModel):
# Will use the original ModelMeta
a=3
class A(object):
__metaclass__ = MyMeta # No __metaclass__ in parents: just instantiate
a=4
class B(A):
pass # MyMeta is not called until specified explicitly
# Make sure we did everything right
assert MyModel.a == 1
assert MyNewModel.a == 2
assert MyNewNewModel.a == 3
assert A.a == 4
# Make sure callback() worked
assert hasattr(MyModel, 'washere')
assert hasattr(MyNewModel, 'washere')
assert hasattr(MyNewNewModel, 'washere') # inherited
assert hasattr(A, 'washere')
assert MyModel.washere == 'MyModel!'
assert MyNewModel.washere == 'MyNewModel!'
assert MyNewNewModel.washere == 'MyNewModel!' # inherited, so unchanged
assert A.washere == 'A!'
答案 0 :(得分:12)
一个类型只能有一个元类,因为元类只是简单地说明了类语句的作用 - 拥有多个元类是没有意义的。出于同样的原因,“链接”没有任何意义:第一个元类创建了类型,那么第二个应该做什么?
您必须合并两个元类(就像任何其他类一样)。但这可能很棘手,特别是如果你真的不知道他们做了什么。
class MyModelBase(type):
def __new__(cls, name, bases, attr):
attr['MyModelBase'] = 'was here'
return type.__new__(cls,name, bases, attr)
class MyMixin(type):
def __new__(cls, name, bases, attr):
attr['MyMixin'] = 'was here'
return type.__new__(cls, name, bases, attr)
class ChainedMeta(MyModelBase, MyMixin):
def __init__(cls, name, bases, attr):
# call both parents
MyModelBase.__init__(cls,name, bases, attr)
MyMixin.__init__(cls,name, bases, attr)
def __new__(cls, name, bases, attr):
# so, how is the new type supposed to look?
# maybe create the first
t1 = MyModelBase.__new__(cls, name, bases, attr)
# and pass it's data on to the next?
name = t1.__name__
bases = tuple(t1.mro())
attr = t1.__dict__.copy()
t2 = MyMixin.__new__(cls, name, bases, attr)
return t2
class Model(object):
__metaclass__ = MyModelBase # inherits from `ModelBase`
class MyModel(Model):
__metaclass__ = ChainedMeta
print MyModel.MyModelBase
print MyModel.MyMixin
正如您所看到的,这已经涉及一些猜测,因为您并不真正知道其他元类的功能。如果两个元类都非常简单,那么可能可以工作,但我不会对这样的解决方案有太多的信心。
为合并多个碱基的元类编写元类是留给读者的练习;-P
答案 1 :(得分:6)
我不知道“混合”元类的任何方法,但你可以像普通类一样继承和覆盖它们。
说我有一个BaseModel:
class BaseModel(object):
__metaclass__ = Blah
现在你想在一个名为MyModel的新类中继承它,但是你想在元类中插入一些额外的功能,但是原来的功能保持不变。要做到这一点,你会做类似的事情:
class MyModelMetaClass(BaseModel.__metaclass__):
def __init__(cls, *args, **kwargs):
do_custom_stuff()
super(MyModelMetaClass, cls).__init__(*args, **kwargs)
do_more_custom_stuff()
class MyModel(BaseModel):
__metaclass__ = MyModelMetaClass
答案 2 :(得分:4)
我认为你不能像那样把它们联系起来,而且我也不知道它是如何起作用的。
但是你可以在运行时创建新的元类并使用它们。但这是一个可怕的黑客。 :)
zope.interface做了类似的事情,它有一个顾问程序元类,它只会在构造后对类做一些事情。如果已经存在一个元类,那么它将要做的事情之一就是将先前的元类设置为元类一旦完成。
(但是,除非必须这样做,否则请避免做这些事情,或者认为这很有趣。)
答案 3 :(得分:0)
在@jochenritzel的回答中,以下内容简化了合并步骤:
def combine_classes(*args):
name = "".join(a.__name__ for a in args)
return type(name, args, {})
class ABCSomething(object, metaclass=combine_classes(SomethingMeta, ABCMeta)):
pass
此处,type(name, bases, dict)
的工作方式类似于动态class
语句(请参见docs)。令人惊讶的是,似乎没有办法使用dict
参数在第二步中设置metaclass
。否则,可以将整个过程简化为一个函数调用。