[英]Python: How to call a parent class (super()) method with using objects from children's attributes?
EDIT: I am having trouble with calling a method of the parent class.编辑:我在调用父 class 的方法时遇到问题。
from datetime import datetime
class GlobalState:
def __init__(self, ui):
self.state = "old"
self.dict_stateWidgets = {"date": None,
"time": None,
"image": None}
self.setState("old")
def setState(self, str_newState: str):
self.state = str_newState
self.updateControlledWidgets()
def extractDateAndTime(self):
dict_dateTime = {"date": str(),
"time": str()}
timestamp = datetime.fromtimestamp(1434549820776 / 1000)
dict_dateTime["date"] = timestamp.strftime("%Y.%m.%d")
dict_dateTime["time"] = timestamp.strftime("%H:%M:%S")
return dict_dateTime
def updateTimeWidget(self):
dict_dateTime = self.extractDateAndTime()
self.dict_stateWidgets["date"].setText(dict_dateTime["date"])
self.dict_stateWidgets["time"].setText(dict_dateTime["time"])
def updateControlledWidgets(self):
self.updateTimeWidget()
class CloudState(GlobalState):
def __init__(self, main_ui):
super().__init__(ui=main_ui)
self.ui = main_ui
self.dict_stateWidgets = {"date": self.ui.l_cloud_date,
"time": self.ui.l_cloud_time,
"image": self.ui.l_cloud_image}
def setState(self, str_newState: str):
super().setState(str_newState)
print("Some more class-specific actions to be done here")
class Widget():
def __init__(self, name):
self.name = name
def setText(self, str_text):
print(str_text)
class MainWindow:
def __init__(self):
self.l_cloud_date = Widget("date")
self.l_cloud_time = Widget("time")
self.l_cloud_image = Widget("image")
if __name__ == '__main__':
ui = MainWindow()
cs = CloudState(ui)
cs.setState("newState")
Expected output: Print output of self.ui.l_cloud_date.setText()预期 output:打印 self.ui.l_cloud_date.setText() 的 output
Error:错误:
in updateTimeWidget self.dict_stateWidgets["date"].setText(dict_dateTime["date"]) AttributeError: 'NoneType' object has no attribute 'setText'
在 updateTimeWidget self.dict_stateWidgets["date"].setText(dict_dateTime["date"]) AttributeError: 'NoneType' object 没有属性 'setText'
I thought I could implement the function in GlobalState and inherit it to CloudState and the super() operator just works with the CloudState object in the GlobalState-implementation... Can someone help?我以为我可以在 GlobalState 中实现 function 并将其继承给 CloudState,而 super() 运算符仅与 GlobalState 实现中的 CloudState object 一起使用...有人可以帮忙吗?
The solution was to remove解决方案是删除
self.setState("old").
It was quite a big code already and I did not see that setState worked with the GlobalState constructor attributes.这已经是相当大的代码了,我没有看到 setState 与 GlobalState 构造函数属性一起使用。
Thanks to chepner for the hint and of course thanks to all of you for your help.感谢 chepner 的提示,当然也感谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.