亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何引用 __init__ 超類中定義的函數

如何引用 __init__ 超類中定義的函數

尚方寶劍之說 2023-06-20 15:15:03
def convert(dictionary我的類中有一個輔助函數 ( )__init__來協助配置設置。定義如下:class Configuration:    def __init__(self, config_file=None, config=None):        if config_file is not None:            with open(config_file) as in_file:                self._config = yaml.load(in_file, Loader=yaml.FullLoader)        elif config is not None:            self._config = config        else:            raise ValueError("Could not create configuration. Must pass either location of config file or valid "                             "config.")        def convert(dictionary):            return namedtuple('Config', dictionary.keys())(**dictionary)這使我可以按如下方式撥打電話__init__:        self.input = convert(self._config["input"])        self.output = convert(self._config["output"])        self.build = convert(self._config["build_catalog"])由于我要設置多個配置,因此我想從他的類中繼承如下:class BuildConfiguration(Configuration):    def __init__(self, config_file=None, config=None):        super().__init__(config_file, config)        self.input = convert(self._config["input"])        self.output = convert(self._config["output"])        self.build = convert(self._config["build_catalog"])convert但是,我無法從父類訪問。我也試過這個:self.input = super().__init__.convert(self._config["input"])這似乎也行不通。所以問題是如何訪問super().__init__子類中定義的函數?
查看完整描述

1 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

你不能。每次調用都會創建一個新函數,__init__然后將其丟棄,它不存在于函數之外。請注意,這也適用于由創建的類namedtuple('Config', dictionary.keys())(**dictionary)。繼續創建所有這些不必要的類確實不好,這完全違背了namedtuple創建內存高效記錄類型的目的。在這里,每個實例都有自己的類!


以下是您應該如何定義它:


Config = namedtuple('Config', "foo bar baz")


def convert(dictionary): # is this really necessary?

    return Config(**dictionary) 


class Configuration:


    def __init__(self, config_file=None, config=None):


        if config_file is not None:

            with open(config_file) as in_file:

                self._config = yaml.load(in_file, Loader=yaml.FullLoader)

        elif config is not None:

            self._config = config

        else:

            raise ValueError("Could not create configuration. Must pass either location of config file or valid "

                             "config.")


        self.input = convert(self._config["input"])

        self.output = convert(self._config["output"])

        self.build = convert(self._config["build_catalog"])

雖然在這一點上,使用它似乎更干凈


Config(**self._config["input"])

etc 而不是 helper convert。


查看完整回答
反對 回復 2023-06-20
  • 1 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號