您可以将
metadocument()元类用作工厂来产生 替换 您的
document类的类,从而重新使用类属性:
class document(object): # various and sundry methods and attributesbody = vars(document).copy()body.pop('__dict__', None)body.pop('__weakref__', None)document = metadocument(document.__name__, document.__bases__, body)这不需要您手动构建第三个参数,即类主体。
您可以将其变成类装饰器:
def with_metaclass(mcls): def decorator(cls): body = vars(cls).copy() # clean out class body body.pop('__dict__', None) body.pop('__weakref__', None) return mcls(cls.__name__, cls.__bases__, body) return decorator然后用作:
@with_metaclass(metadocument)class document(object): # various and sundry methods and attributes
或者,为此使用
six库:
@six.add_metaclass(metadocument)class document(object):
其中,
@six.add_metaclass()装饰也需要的任何照顾
__slots__你可能已经定义;
我上面的简单版本没有。
six还有一个
six.with_metaclass()基层工厂:
class document(six.with_metaclass(metadocument)):
这为MRO注入了额外的基类。



