PHP前端开发

Python 3.12中__int__写错导致报错:如何正确初始化类属性?

百变鹏仔 2个月前 (01-14) #Python
文章标签 报错

python 3.12 中使用 class __init__* 属性报错

在 python 3.12 中编写代码时,你遇到了一个错误,提示找不到一个类属性。错误信息指出,对象没有名为 confname 的属性。

仔细检查你的代码后,我们会发现问题出在 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_hostif __name__ == "__main__":    gc1 = GetConfig()    var = gc1.get_db_host()

更正之后,代码应该可以正确运行,并且能够访问类属性 confname