关于python中的类属性和实例属性

学的时候我以为我懂了,遇到问题的时候我发现,其实我没懂,请看示例:

python 复制代码
class TestConfigObject:
    config_file_name = "default"

    def __init__(self, context=None, *args, **kwargs):
        self.config_file_name = "2"

class TestChild(TestConfigObject):
    def __init__(self):
        super().__init__()
        self.config_file_name = "3"

if __name__=="__main__":
    TestConfigObject.config_file_name = "1"
    print("应该为1:" + str(TestConfigObject.config_file_name))
    test2 = TestConfigObject()
    print("应该为2:"+str(test2.config_file_name))
    print("应该为2:"+str(TestConfigObject.config_file_name))
    test3 = TestChild()
    print("应该为3:" + str(test3.config_file_name))
    print("应该为3:" + str(TestConfigObject.config_file_name))
    print("应该为3:" + str(test2.config_file_name))

打印出来:

应该为1:1

应该为2:2

应该为2:1

应该为3:3

应该为3:1

应该为3:2

应该为的值 是我开始我的理解,实际上不是这样。因为

config_file_name 被定义为类属性,但在 __init__ 方法中,你尝试将其赋值给 self.config_file_name,这实际上创建了一个实例属性,覆盖了类属性。因此,当你访问 test2.config_file_nametest3.config_file_name 时,你访问的是实例属性,而不是类属性。

要实现类属性和实例属性的共享,需要确保在实例方法中修改的是类属性,而不是创建一个新的实例属性。以下是修改后的代码:

python 复制代码
class TestConfigObject:
    config_file_name = "default"

    def __init__(self, context=None, *args, **kwargs):
        TestConfigObject.config_file_name = "2"

class TestChild(TestConfigObject):
    def __init__(self):
        super().__init__()
        TestConfigObject.config_file_name = "3"

if __name__=="__main__":
    TestConfigObject.config_file_name = "1"
    print("应该为1:" + str(TestConfigObject.config_file_name))
    test2 = TestConfigObject()
    print("应该为2:"+str(test2.config_file_name))
    print("应该为2:"+str(TestConfigObject.config_file_name))
    test3 = TestChild()
    print("应该为3:" + str(test3.config_file_name))
    print("应该为3:" + str(TestConfigObject.config_file_name))
    print("应该为3:" + str(test2.config_file_name))
相关推荐
我材不敲代码1 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
0思必得03 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
韩立学长4 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
qq_192779874 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u0109272714 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊4 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
Imm7774 小时前
中国知名的车膜品牌推荐几家
人工智能·python
tudficdew5 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd6525 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
2301_821369615 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python