3

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

当我在父类中定义变量时,在父类中继承的任何子类都从父类引用相同的变量。

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的每个类中创建字典实例。所以引用会提高ChildParentChildB.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

那么有什么方法可以实现我想要的行为吗?

4

1 回答 1

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'
于 2013-11-10T16:30:30.643 回答