Python 3.12中`__int__`导致属性不可用:为什么我的GetConfig对象没有\’conf\’属性?
学习要努力,但是不要急!今天的这篇文章《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()
错误消息:
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\’属性?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注公众号!