本文分析了在 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类中调用属性时报错“属性不存在”?的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论