python - 你如何解释这个 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
解决方案
推荐阅读
- excel - Excel 2016 VBA 女士如何使用 .top 和 .left
- kubernetes - 在 spin-redis-bootstrap 阶段将 Spinnaker 部署到 Openshift 失败
- java - 通过 Jena 权限示例教程获取 NoClassDefFoundError
- c# - 从字符串中转义定义的特殊字符
- java - Java - 如何将方形数组(二维)向右旋转 90 度?
- docker - Go 1.11 Docker build 中自己的包的未知导入路径
- r - 自定义R中的排序功能
- raspberry-pi - 播放视频时,Raspberry Pi 3 上的 Gstreamer 噼啪声
- oracle - 为什么我的 Oracle ORDS 插件不起作用?
- excel - 如果 X 和 Y 为空,则邮件合并跳过