我想我误解了类型继承在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
)
那么有没有办法实现我想要的行为?
答案 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'