关于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))
相关推荐
Eiceblue15 分钟前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_5275504027 分钟前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂1 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP2 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@2 小时前
Python数据分析7
开发语言·python
老胖闲聊3 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
码界奇点3 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI3 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python
行云流水剑4 小时前
【学习记录】如何使用 Python 提取 PDF 文件中的内容
python·学习·pdf
心扬5 小时前
python生成器
开发语言·python