Python 3.12中`__int__`导致属性不可用:为什么我的GetConfig对象没有'conf'属性?

ID:21502 / 打印

python 3.12中`__int__`导致属性不可用:为什么我的getconfig对象没有'conf'属性?

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 Selenium多线程爬虫报错:并发执行失败的原因是什么?
下一篇: Python脚本如何清空终端之前的输出?

作者:admin @ 24资源网   2025-01-14

本站所有软件、源码、文章均有网友提供,如有侵权联系308410122@qq.com

与本文相关文章

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。