Python方法改变自身值(dict-inherited class)

时间:2018-03-27 16:57:43

标签: python oop methods

我有一个看起来像字典的自定义类,我想要一个能够修改字典值的方法,但不知怎的,我似乎只能通过逐个键修改来实现这一点(而不是self=...分配。

显然我想要一些比下面的MWE更复杂的东西,但它证明了我的问题(我希望下面的两个类方法都是等价的):

class MyClass(dict):
    def addone_notworking(self):
        self = {key: (val+1) for key, val in self.items()}
        # print({key: (val+1) for key, val in self.items()}) would return what I expect

    def addone_working(self):
        for k in self:
            self[k] += 1  # self[k] = self[k] + 1 would work as well

a = MyClass({'a':1, 'b':2})
print(a, '<-- original')
a.addone_notworking()
print(a, "<-- should have added 1, but it hasn't")
a.addone_working()
print(a, '<-- works')

结果:

{'a': 1, 'b': 2} <-- original
{'a': 1, 'b': 2} <-- should have added 1, but hasn't
{'a': 2, 'b': 3} <-- works

我错过了什么?我找到了Python class methods changing self,但我怀疑它是否真的适用(bar = foo语句即使bar是非可变类型也会有效。)

(Python 3.5,如果重要的话)

0 个答案:

没有答案