本文介绍了Python元类和对象基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了出色的 SO帖子之后,我尝试了制作模块级元类:

After reading the excellent SO post, I tried crafting a module level metaclass:

def metaclass(future_class_name, future_class_parents, future_class_attrs):
    print "module.__metaclass__"
    future_class_attrs["bar"]="bar"
    return type(future_class_name, future_class_parents, future_class_attrs)

__metaclass__=metaclass


class Foo(object):

    def __init__(self):
        print 'Foo.__init__'

f=Foo()

除非我删除了Foo的object基类,否则这是行不通的(即,"module.元类"不会被打印).怎么会来?

This doesn't work (i.e. "module.metaclass" doesn't get printed) unless I remove the object base class of Foo. How come?

注意:我正在使用Python 2.6.1.

NOTE: I am using Python 2.6.1.

推荐答案

object 继承会自动带来 type 元类.这会覆盖您的模块级别 __ metaclass __ 规范.

Inheriting from object automatically brings the type metaclass along with it. This overrides your module level __metaclass__ specification.

如果在类级别指定了元类,则 object 不会覆盖它:

If the metaclass is specified at the class level, then object won't override it:

def metaclass(future_class_name, future_class_parents, future_class_attrs):
    print "module.__metaclass__"
    future_class_attrs["bar"]="bar"
    return type(future_class_name, future_class_parents, future_class_attrs)

class Foo(object):
    __metaclass__ = metaclass

    def __init__(self):
        print 'Foo.__init__'

f=Foo()

请参见 http://docs.python.org /reference/datamodel.html?highlight= 元类#customizing-class-creation

See http://docs.python.org/reference/datamodel.html?highlight=metaclass#customizing-class-creation

这篇关于Python元类和对象基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:37