Skip to main content
 首页 » 编程设计

python之在python中使用基类classmethod实例化派生类对象

2025年04月02日16zlslch

我有一个像下面这样的基类:

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) 

然后我希望能够在派生类中使用类方法构造函数。天真地,我试过:

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)