Python继承了类型变量

时间:2013-11-10 16:23:50

标签: python inheritance types

我想我误解了类型继承在python中是如何工作的。

虽然我在Parent类中定义变量,但在父类中继承的任何Child类 从父级引用相同的变量。

class Parent(object):
    store = dict()

class ChildA(Parent):
   pass

class ChildB(Parent):
   pass

ChildA.store['key1'] = 'val' 
ChildB.store['key2'] = 'val'

print ChildB.store['key1'] == ChildA.store['key2']

我想要实现的是在store继承的每个Child类中创建Parent字典实例。因此引用ChildB.store['key1']会引发KeyError

我尝试在类型创建时使用__new__创建字典实例:

class NewParent(object):  
    def __new__(cls, *args, **kwargs):
        rv = super(NewParent,cls).__new__(cls, *args, **kwargs)
        rv.store = dict()
        return rv

但是在__new__类实例化之前似乎只有Child运行,因此通过类型引用变量(例如Child.store正在提升AttributeError

那么有没有办法实现我想要的行为?

1 个答案:

答案 0 :(得分:3)

您希望使用元类,它允许您初始化类定义,就像构造函数允许您初始化实例一样。有关详细信息,请参阅http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/

示例:

#!/usr/bin/env python2

class ParentMeta(type):
    def __new__(meta, name, bases, dct):
        dct['store'] = dict()
        return super(ParentMeta, meta).__new__(meta, name, bases, dct)

class Parent(object):
    __metaclass__ = ParentMeta

class ChildA(Parent):
    pass

class ChildB(Parent):
   pass

ChildA.store['key1'] = 'val'
ChildB.store['key2'] = 'val'

print ChildB.store['key1'] == ChildA.store['key2']

将导致

Traceback (most recent call last):
  File "test.py", line 20, in <module>
    print ChildB.store['key1'] == ChildA.store['key2']
KeyError: 'key1'