2016-04-14 54 views
1

我无法从子类中的字典中访问超类变量。 下面的代码是一个简化的例子:将超类的变量添加到字典子类并读取值

class SetStuff: 
    def __init__(self): 
     self.temperature = 0.0 

    def set_temp(self, temp): 
     self.temperature = temp 


class DoStuff(SetStuff): 
    def __init__(self): 
     super().__init__() 
     self.info_dict = {"temp": {"current_temp": self.temperature}} 

    def print_stuff(self): 
     print("temp_var:", self.temperature) 
     print("dict:", self.info_dict) 



test_stuff = DoStuff() 
test_stuff.set_temp(12.1) 
test_stuff.print_stuff() 

最后调用的结果是:

temp_var: 12.1 
dict: {'temp': {'current_temp': 0.0}} 

尽管我的预期印刷字典包含12.1。我似乎无法理解这里发生了什么,以及我如何解决这个问题。

任何帮助将不胜感激。

回答

1

看看self.info_dict的设置。它在__init__所以self.temperature的价值的确是零current_temp,因为它被设置为self.temperature

+0

感谢您的解释的初始值,是有道理的。有没有办法将上述变量更新为当前值? –

+0

你可以做'self.info_dict ['temp'] ['current_temp'] = self.temperature',但如果你需要这个值,你可以调用这个属性。不清楚为什么'字典'在这里会很有用。如果你只需要调用这个值,那么dict对此有点多余。如果你真的想,你甚至可以索引'self .__ dict __ ['temperature']'而不是调用'self.temperature'。 – Pythonista