Python继承的类型变量

我想我误会了Python中类型继承的工作方式.

当我在Parent类中定义变量时,任何在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']

我想要实现的是要在从Parent继承的每个Child类中创建商店字典实例.因此,引用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)

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

解决方法:

您想使用一个元类,它使您可以初始化类定义,就像构造函数如何初始化实例一样.有关更多详细信息,请参见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'
上一篇:java-泛型类型和toArrayMethod


下一篇:Java选择性泛型