Python:如何调用父类(super())方法并使用子类属性中的对象?

2uluyalo  于 2023-01-16  发布在  Python
关注(0)|答案(1)|浏览(194)
    • EDIT:**调用父类的方法时遇到问题。

1.工作代码示例:

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")

1.预期产出:打印self. ui. l_cloud_date. setText()的输出
1.错误:
在更新时间小部件自身中。dict_state小部件["日期"]。setText(dict_日期时间["日期"])属性错误:"NoneType"对象没有属性"setText"
我想我可以在GlobalState中实现这个函数,并将其继承给CloudState,而super()操作符只与GlobalState实现中的CloudState对象一起工作......有人能帮忙吗?

jhdbpxl9

jhdbpxl91#

解决办法是

self.setState("old").

这已经是一段相当大的代码了,我没有看到setState与GlobalState构造函数属性一起工作。
感谢chepner的提示,当然也感谢你们所有人的帮助。

相关问题