python3.12 为什么无法调用__init__中的属性?

使用了python 3.12编写下列程序 运行时报错

class GetConfig(object):
    def __int__(self):
        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()

报错信息:

Traceback (most recent call last):
  File "D:\Code\InterfaceCrawlTool\getConfig.py", line 48, in <module>
    var = gc1.get_db_host()
          ^^^^^^^^^^^^^^^^^
  File "D:\Code\InterfaceCrawlTool\getConfig.py", line 21, in get_db_host
    db_host = self.conf.get("DB", "host")
              ^^^^^^^^^
AttributeError: 'GetConfig' object has no attribute 'conf'

为什么会提示找不到属性呢?我尝试在__init__方法中加入self.name="test",然后使用
gc1 = GetConfig()
gc1.name 也是报同样的错误

阅读 1.4k
avatarAI BotBETA

在你的代码中,你尝试在类的构造函数 __init__ 中定义一个属性 conf,但这个属性只在该函数的作用域内存在,所以它不能在类的其他方法中被访问。

在 Python 中,self 参数表示类的实例,而 self.conf 是在 __init__ 方法中定义的实例变量。这意味着,只有当你在类的实例化过程中(即创建类的对象时)调用 __init__ 方法时,这个属性才会被创建。一旦 __init__ 方法执行完毕,这个属性就不再存在,这就是为什么你在 get_db_host 方法中无法访问 self.conf 的原因。

要解决这个问题,你可以将 self.conf 的定义移出 __init__ 方法,直接在类中定义,就像这样:

class GetConfig(object):
    def __init__(self):
        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

这样,self.conf 就会在类的实例化过程中被创建,并且在类的其他方法中都可以被访问。

2 个回答
✓ 已被采纳

你写的是__int__,不是__init__

Dube, 尽管他们很相似, 但是双胞胎也是有区别的。你写的是 __int__, 少了字母 i, 那可就不是python官方承认的 __init__了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题