关于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))
相关推荐
u***32432 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql
青瓷程序设计4 小时前
动物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
tobebetter95274 小时前
How to manage python versions on windows
开发语言·windows·python
F_D_Z4 小时前
数据集相关类代码回顾理解 | sns.distplot\%matplotlib inline\sns.scatterplot
python·深度学习·matplotlib
daidaidaiyu5 小时前
一文入门 LangGraph 开发
python·ai
不知更鸟6 小时前
前端报错:快速解决Django接口404问题
前端·python·django
4***72136 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
梁正雄6 小时前
1、python基础语法
开发语言·python
ituff8 小时前
微软认证考试又免费了
后端·python·flask
梁正雄9 小时前
2、Python流程控制
开发语言·python