1

How can you explain the output of the following program?

To me, it looks like, MyClass is maintaining two copies of __my_variable in later stages. Then, why is __init__() able to display "Hello World!"?

To my understanding __init__() should print a blank. Right?

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

Output

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
user366312
  • 16,949
  • 65
  • 235
  • 452

0 Answers0