
python 3.12 中使用 class __init__* 属性报错
在 python 3.12 中编写代码时,你遇到了一个错误,提示找不到一个类属性。错误信息指出,对象没有名为 conf 或 name 的属性。
仔细检查你的代码后,我们会发现问题出在 class getconfig 的构造函数名称上。你写的是 __int__,而不是 __init__。在 python 中,特殊的双下划线方法通常用于特定目的。
__init__ 是类的构造方法,它在创建对象时被调用。它用于初始化对象的属性。而 __int__ 是用来将对象表示为整数时的特殊方法。
立即学习“Python免费学习笔记(深入)”;
解决方法:
为了解决这个问题,你需要将 __int__ 更正为 __init__。以下是更正后的代码:
class GetConfig(object):
def __init__(self): # 改为 __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()更正之后,代码应该可以正确运行,并且能够访问类属性 conf 和 name。
以上就是Python 3.12中__int__写错导致报错:如何正确初始化类属性?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号