你如何解释这个 Python 程序的输出?

问题描述

你如何解释以下程序的输出

在我看来,MyClass 在后期维护 __my_variable 的两个副本。那么,为什么__init__()可以显示"Hello World!"

据我所知,__init__() 应该打印一个空白。对吗?

class MyClass:
    __my_variable: str = "Hello World!"

    def __init__(self):
        print(self.__my_variable)
        self.__my_variable = "Constructor World!"

    @classmethod
    def cls_modify(cls):
        cls.__my_variable = "Class World!"

    @classmethod
    def cls_display(cls):
        print(cls.__my_variable)

    def inst_modify(self):
        self.__my_variable = "Instance World!"

    def inst_display(self):
        print(self.__my_variable)


if __name__ == '__main__':
    my_obj = MyClass()
    my_obj.cls_display()
    my_obj.inst_display()
    my_obj.cls_modify()
    my_obj.cls_display()
    my_obj.inst_display()
    my_obj.inst_modify()
    my_obj.cls_display()
    my_obj.inst_display()

输出

C:\Users\pc\AppData\Local\Microsoft\WindowsApps\python3.7.exe C:/Users/pc/source/classmethod__test.py
Hello World!
Hello World!
Constructor World!
Class World!
Constructor World!
Class World!
Instance World!

Process finished with exit code 0

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)