
本文分析并解决了一个 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_hostif __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 osimport configparserclass 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_hostif __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 的大小写必须与实际情况一致。
以上就是为什么在Python中无法调用类初始化方法中定义的属性?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1359617.html
微信扫一扫
支付宝扫一扫