编程语言
首页 > 编程语言> > Python:动态类生成:覆盖成员

Python:动态类生成:覆盖成员

作者:互联网

我有一个python类层次结构,我想在运行时扩展.此外,此层次结构中的每个类都有一个静态属性“dict”,我想在每个子类中覆盖它.简化它看起来像这样:

‘dict’是受保护的(公共但具有领先的下划线)成员

class A(object):
    _dict = {}

    @classmethod
    def getdict(cls):
        return cls._dict

    @classmethod
    def setval(cls, name, val):
        cls._dict[name] = val

    @classmethod
    def addchild(cls, name):
        return type(name, (cls, ), { '_dict' : {} })

B = A.addchild('B')
A.setval(1, 5)

print A.getdict()
# prints: {1: 5}
# like expected

print B.getdict()
# prints: {}
# like expected

这与预期一样有效.现在的问题是:如果我将属性声明为private,为什么它不再起作用:

现在和’dict’一样私有成员

class C(object):
    __dict = {}

    @classmethod
    def getdict(cls):
        return cls.__dict

    @classmethod
    def setval(cls, name, val):
        cls.__dict[name] = val

    @classmethod
    def addchild(cls, name):
        return type(name, (cls, ), { '__dict' : {} })

D = C.addchild('D')
C.setval(1, 5)

print C.getdict()
# prints: {1: 5}
# like expected

print D.getdict()
# prints: {1: 5}
# why!?

突然D,C的子类,在’dict’中具有与其超类相同的值!?

谁能这么善良并向我解释,原因是什么?提前致谢!

解决方法:

phild,如你所知,当你使用双下划线__为属性名称添加前缀时,python解释器会自动将(mangles)属性名称从__attribute更改为_CLS__attribute,其中CLS是类名.

但是,当你说

返回类型(name,(cls,),{‘__ dict’:{}})

字典中的键{‘__dict’:{}}不会被破坏. __dict保持不变.

因此D最终得到D._C__dict和D .__ dict:

(Pdb) dir(D)
['_C__dict', '__class__', '__delattr__', '__dict', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'addchild', 'getdict', 'setval']

D._C__dict是指C的类属性.所以当你跑步的时候

C.setval(1,5)

你正在改变D._C__dict以及C._C__dict.他们是一样的.

标签:python,inheritance,name-mangling,dynamic-class-creation
来源: https://codeday.me/bug/20190607/1192059.html