为什么在Python中无法调用类初始化方法中定义的属性?

为什么在Python中无法调用类初始化方法中定义的属性?

本文分析并解决了一个 python 3.12 程序中,无法在类方法中访问在 __init__ 方法中定义的属性的问题。

问题代码及错误:

以下代码片段演示了错误:

class getconfig(Object):     def __int__(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()

运行这段代码会抛出 AttributeError: ‘getconfig’ object has no attribute ‘conf’ 的错误。

立即学习Python免费学习笔记(深入)”;

错误原因:

错误的原因在于 __int__ 的错误拼写。Python 中类的构造方法必须命名为 __init__。由于使用了 __int__,导致 self.conf 属性从未被初始化,因此在 get_db_host 方法中访问 self.conf 时会引发错误。

解决方案:

将 __int__ 更正为 __init__,并对 configparser 进行大小写调整(假设 sysConfig.cfg 文件存在):

import os import configparser  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") # Assuming DB section in sysConfig.cfg         return db_host  if __name__ == "__main__":     gc1 = GetConfig()     var = gc1.get_db_host()     print(var) # Print the result to verify

这个修改后的代码将正确初始化 self.conf 属性,从而允许 get_db_host 方法访问它。 请确保 sysConfig.cfg 文件存在于正确的路径下,并且包含一个名为 “DB” 的 section,其中包含 “host” 键值对

通过更正 __init__ 的拼写,以及对配置文件路径和 section 名称的检查,这个问题就能得到有效解决。 记住,Python 对大小写敏感,因此 configparser 和 sysConfig.cfg 的大小写必须与实际情况一致。

以上就是

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享