為什么在Python中無法調(diào)用類初始化方法中定義的屬性?

為什么在Python中無法調(diào)用類初始化方法中定義的屬性?

本文分析并解決了一個 python 3.12 程序中,無法在類方法中訪問在 __init__ 方法中定義的屬性的問題。

問題代碼及錯誤:

以下代碼片段演示了錯誤:

class getconfig(Object):     def __int__(self):  # 錯誤:應(yīng)該是 __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()

運(yùn)行這段代碼會拋出 AttributeError: ‘getconfig’ object has no attribute ‘conf’ 的錯誤。

立即學(xué)習(xí)Python免費(fèi)學(xué)習(xí)筆記(深入)”;

錯誤原因:

錯誤的原因在于 __int__ 的錯誤拼寫。Python 中類的構(gòu)造方法必須命名為 __init__。由于使用了 __int__,導(dǎo)致 self.conf 屬性從未被初始化,因此在 get_db_host 方法中訪問 self.conf 時會引發(fā)錯誤。

解決方案:

將 __int__ 更正為 __init__,并對 configparser 進(jìn)行大小寫調(diào)整(假設(shè) 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 的大小寫必須與實(shí)際情況一致。

以上就是

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊10 分享