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。我似乎無法理解這裏發生了什麼,以及我如何解決這個問題。
任何幫助將不勝感激。
感謝您的解釋的初始值,是有道理的。有沒有辦法將上述變量更新爲當前值? –
你可以做'self.info_dict ['temp'] ['current_temp'] = self.temperature',但如果你需要這個值,你可以調用這個屬性。不清楚爲什麼'字典'在這裏會很有用。如果你只需要調用這個值,那麼dict對此有點多餘。如果你真的想,你甚至可以索引'self .__ dict __ ['temperature']'而不是調用'self.temperature'。 – Pythonista