為什么在Python 3.12中無(wú)法調(diào)用__init__中的屬性?

為什么在Python 3.12中無(wú)法調(diào)用__init__中的屬性?

本文分析了python 3.12中一個(gè)常見(jiàn)的類屬性訪問(wèn)錯(cuò)誤,并提供了詳細(xì)的解決方案。

問(wèn)題:在Python 3.12中,嘗試訪問(wèn)在__init__方法中定義的類屬性時(shí),出現(xiàn)AttributeError,提示屬性不存在。

代碼示例:

class getconfig(object):     def __int__(self):  # 錯(cuò)誤:應(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()

錯(cuò)誤原因:代碼中__int__方法拼寫(xiě)錯(cuò)誤,應(yīng)為_(kāi)_init__。Python解釋器將__int__視為普通方法,而不是構(gòu)造方法,因此在創(chuàng)建getconfig對(duì)象時(shí),self.conf屬性未被初始化。

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

解決方案:將__int__更正為_(kāi)_init__,并建議使用更規(guī)范的命名方式:

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")  #建議文件名規(guī)范化         self.conf = configparser.ConfigParser()         self.conf.read(sys_cfg_file)      def get_db_host(self):         db_host = self.conf.get("DB", "host") #建議鍵名規(guī)范化         return db_host  if __name__ == "__main__":     gc1 = GetConfig()     var = gc1.get_db_host()     print(var) #添加打印結(jié)果方便調(diào)試

通過(guò)更正__init__方法的拼寫(xiě)錯(cuò)誤,并對(duì)代碼進(jìn)行一些規(guī)范化處理,可以解決AttributeError問(wèn)題,成功訪問(wèn)self.conf屬性。 記住,Python對(duì)大小寫(xiě)敏感,__init__和__int__是完全不同的方法。 此外,規(guī)范的代碼風(fēng)格能提高可讀性和可維護(hù)性。

以上就是

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