首页 > 解决方案 > 你如何解释这个 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

标签: pythonmodulestatistics

解决方案


推荐阅读