簡體   English   中英

在python中使用基類classmethod實例化派生類對象

[英]instantiating a derived class object with a base class classmethod in python

我有一個基類,如下所示:

class Base(object):
    def __init__(self, arg1, arg2):
        #Declare self
        self.arg1 = arg1
        self.arg2 = arg2

    @classmethod
    def from_ini_file(cls, f):
        # Get arg1 and arg2 from ini file
        return cls(arg1, arg2)

然后我希望能夠在派生類中使用 classmethod 構造函數。 天真地,我試過:

class Derived(Base):
    def __init__(self):
        f = 'default.ini'
        Base.from_ini_file(f)

但這不起作用。 我想我明白為什么這不起作用,但如果可能的話,我一直無法弄清楚如何正確地做到這一點。

感謝您的任何幫助。

編輯

這感覺很不雅,但我目前正在使用:

class Derived(Base):
    def __init__(self):
        t = Base.from_ini_file('default.ini')
        Base.__init__(t.arg1, t.arg2)

這里有很多多余的操作,我不喜歡必須有 Base 的參數。 init函數必須以這種方式保存到對象中以供使用。 所以我全神貫注於更好的解決方案。 再次感謝。

from_ini_file返回一個新實例,所以你必須從你的派生類調用這個方法也形成一個類方法:

class Derived(Base):
    @classmethod
    def from_default_ini(cls):
        f = 'default.ini'
        return cls.from_ini_file(f)

我知道這太舊了,我相信你已經繼續前進了,但我想我會分享我如何實現類似的東西

class Base(object):
    def __init__(self, arg1, arg2):
        #Declare self
        self.arg1 = arg1
        self.arg2 = arg2

    @staticmethod
    def from_ini_file(f):
        # Get arg1 and arg2 from ini file
        return Base(arg1, arg2)
myInstance = Base.from_ini_file(f)

如果您想完全隱藏 ini 文件:

class Derived(Base):
    def __init__(self, f='default.ini'):
        # Get arg1 and arg2 from ini file
        super().__init__(arg1, arg2)
defaultInstance = Derived()
customInstance = Derived(customF)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM