Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python中的基类类方法实例化派生类对象_Python - Fatal编程技术网

用python中的基类类方法实例化派生类对象

用python中的基类类方法实例化派生类对象,python,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

我有一个基类,如下所示:

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)

这里有很多冗余操作,我不喜欢有基的参数。init函数必须保存到对象中,以便以这种方式使用。所以我一直在寻找更好的解决方案。再次感谢。

来自\u ini\u文件
返回一个新实例,因此您必须从派生类调用此方法并形成一个类方法:

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

我知道这是非常古老的,我相信你已经离开了,但我想我会分享一下我是如何实现类似的东西的

类基(对象):
定义初始化(self,arg1,arg2):
#声明自己
self.arg1=arg1
self.arg2=arg2
@静力学方法
来自_ini_文件(f)的def:
#从ini文件获取arg1和arg2
返回基数(arg1、arg2)
myInstance=Base.from_ini_文件(f)
如果要完全隐藏ini文件,请执行以下操作:

派生类(基):
def uuu init uuuu(self,f='default.ini'):
#从ini文件获取arg1和arg2
super()。\uuuu初始化(arg1,arg2)
defaultInstance=Derived()
customInstance=派生(customF)

感谢您的快速响应!很抱歉过于密集,但您基本上是在告诉我,我无法从派生类的
\uuuu init\uuuu()
中调用classmethod。这有点不令人满意,因为派生类的一个要点是抽象默认实例化信息的来源。也就是说,我不希望用户关心源代码是否使用ini文件来构造基本对象。他们只是使用默认构造操作启动派生对象。这有意义吗?