将超类的变量添加到字典子类并读取值
Add variable of superclass to dictionary subclass and read value
我无法从子类中的字典访问超类变量。
下面的代码是一个简化的例子:
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。我似乎无法理解这里发生了什么以及我该如何解决这个问题。
如有任何帮助,我们将不胜感激。
查看 self.info_dict
的设置位置。它在 __init__
中,所以 self.temperature 的值对于 current_temp
确实为零,因为它被设置为 self.temperature
的 initial 值
我无法从子类中的字典访问超类变量。 下面的代码是一个简化的例子:
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。我似乎无法理解这里发生了什么以及我该如何解决这个问题。
如有任何帮助,我们将不胜感激。
查看 self.info_dict
的设置位置。它在 __init__
中,所以 self.temperature 的值对于 current_temp
确实为零,因为它被设置为 self.temperature
的 initial 值