首页 > 关于python 元类的理解

关于python 元类的理解

class SettingMeta(object):
    def __new__(cls,*args,**kwargs):
        import pdb;pdb.set_trace()
        print "new"
        return super(SettingMeta1,cls).__new__(cls,*args,**kwargs)
    def __init__(self,*args):
        print "init"

Setting = SettingMeta('Setting', (object,), {})
class Bind(Setting):
    action = "append"
    def add1(self):
        print "123"

此时Setting 是SettingMeta的实例,为什么加载Bind的时候会调用SettingMeta.new?
不太理解。。。


不知道怎么搞的,Python 就是这么个逻辑。

reference/datamodel.html#determining-the-appropriate-metaclass 这节,第三点,「or」后半句:

[if] bases are defined, then the most derived metaclass is used

你别的都没做,只定义了一个父类,所以 Python 就拿它的的 __class__ 当元类用。但是它不是个类啊,所以它的 __class__ 不是 type,而是你的 SettingMeta。于是 SettingMeta 就成这个 Bind 类的元类了……

具体代码见 Python/bltinmodule.c 里的 __build_class__ 内建函数的实现(链接到的地方就是你的 __new__ 被调用的地方)。

我用的是 Python 3 的代码。不过估计 Python 2 那边也是差不多的。

PS: markdown 反人类啊 :-(


元类体现在哪里?

【热门文章】
【热门文章】