為什么在Python類中調用屬性時報錯“屬性不存在”?

為什么在Python類中調用屬性時報錯“屬性不存在”?

本文分析了在 python 3.12 中,因類屬性調用錯誤導致的AttributeError問題。 問題源于一個簡單的拼寫錯誤,導致無法正確初始化類屬性。

問題描述:

代碼在調用 __init__ 方法中定義的屬性時拋出 AttributeError,提示屬性不存在。

錯誤代碼:

立即學習Python免費學習筆記(深入)”;

class getconfig(object):     def __int__(self):  # 拼寫錯誤:__int__ 而不是 __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'

錯誤分析:

__int__ 方法并非 Python 中的構造函數,正確的構造函數名稱是 __init__。由于拼寫錯誤,__init__ 方法未被調用,因此 self.conf 屬性未被初始化,導致 get_db_host 方法嘗試訪問不存在的屬性 conf。

解決方案:

將 __int__ 更正為 __init__,并建議使用更規范的命名方式(例如首字母大寫):

import os import configparser  # 確保已導入 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") # 建議使用大寫 "DB" 保持一致性         return db_host  if __name__ == "__main__":     gc1 = GetConfig()     var = gc1.get_db_host()     print(var) # 打印結果,驗證是否成功

通過這個簡單的更正,代碼就能正常運行,并成功訪問 conf 屬性。 記住,Python 對大小寫敏感,并且遵循一致的命名規范對于代碼的可讀性和可維護性至關重要。

以上就是

? 版權聲明
THE END
喜歡就支持一下吧
點贊12 分享