当前位置: 代码网 > it编程>前端脚本>Python > 为什么在Python类中调用属性时报错“属性不存在”?

为什么在Python类中调用属性时报错“属性不存在”?

2025年03月30日 Python 我要评论
本文分析了在 python 3.12 中,因类属性调用错误导致的attributeerror问题。 问题源于一个简单的拼写错误,导致无法正确初始化类属性。问题描述:代码在调用 __init__ 方法

为什么在python类中调用属性时报错“属性不存在”?

本文分析了在 python 3.12 中,因类属性调用错误导致的attributeerror问题。 问题源于一个简单的拼写错误,导致无法正确初始化类属性。

问题描述:

代码在调用 __init__ 方法中定义的属性时抛出 attributeerror,提示属性不存在。

错误代码:

class getconfig(object):
    def __int__(self):  # 拼写错误:__int__ 而不是 __init__
        current_dir = os.path.dirname(os.path.abspath(__file__))
        print(current_dir)
        sys_cfg_file = os.path.join(current_dir, "sysconfig.cfg")
        self.conf = configparser.configparser()
        self.conf.read(sys_cfg_file)

    def get_db_host(self):
        db_host = self.conf.get("db", "host")
        return db_host

if __name__ == "__main__":
    gc1 = getconfig()
    var = gc1.get_db_host()
登录后复制

错误信息:

attributeerror: 'getconfig' object has no attribute 'conf'
登录后复制

错误分析:

__int__ 方法并非 python 中的构造函数,正确的构造函数名称是 __init__。由于拼写错误,__init__ 方法未被调用,因此 self.conf 属性未被初始化,导致 get_db_host 方法尝试访问不存在的属性 conf。

解决方案:

将 __int__ 更正为 __init__,并建议使用更规范的命名方式(例如首字母大写):

import os
import configparser  # 确保已导入 configparser 模块

class getconfig(object):
    def __init__(self):
        current_dir = os.path.dirname(os.path.abspath(__file__))
        print(current_dir)
        sys_cfg_file = os.path.join(current_dir, "sysconfig.cfg") #建议文件名也使用一致的命名规范
        self.conf = configparser.configparser()
        self.conf.read(sys_cfg_file)

    def get_db_host(self):
        db_host = self.conf.get("db", "host") # 建议使用大写 "db" 保持一致性
        return db_host

if __name__ == "__main__":
    gc1 = getconfig()
    var = gc1.get_db_host()
    print(var) # 打印结果,验证是否成功
登录后复制

通过这个简单的更正,代码就能正常运行,并成功访问 conf 属性。 记住,python 对大小写敏感,并且遵循一致的命名规范对于代码的可读性和可维护性至关重要。

以上就是为什么在python类中调用属性时报错“属性不存在”?的详细内容,更多请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com