python 3.12 中 init 中的属性不可用
在 python 3.12 中编写了一个程序,但是运行时遇到了一个错误,提示“attributeerror:getconfig 对象没有属性 conf”。
错误代码如下:
class getconfig(object): def __int__(self): # 创建一个属性 self.conf = configparser.configparser() def get_db_host(self): return self.conf.get("db", "host") if __name__ == "__main__": gc1 = getconfig() var = gc1.get_db_host()
错误消息:
立即学习“Python免费学习笔记(深入)”;
traceback (most recent call last): file "getconfig.py", line 21, in <module> var = gc1.get_db_host() ^^^^^^^^^^^^^^^^^ file "getconfig.py", line 17, in get_db_host return self.conf.get("db", "host") ^^^^^^^^^ attributeerror: 'getconfig' object has no attribute 'conf'
为什么会出现此错误?
错误的根本原因在于类构造方法的拼写。在 python 中,类构造方法的名称是 __init__,而不是 __int__。
修正后的代码如下:
class GetConfig(object): def __init__(self): # 创建一个属性 self.conf = configparser.ConfigParser() def get_db_host(self): return self.conf.get("DB", "host") if __name__ == "__main__": gc1 = GetConfig() var = gc1.get_db_host()
以上就是Python 3.12中`__int__`导致属性不可用:为什么我的GetConfig对象没有'conf'属性?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号