如何从父类调用子类的构造函数?

4
在继承中,大多数时候我们想要创建从父类继承的子类,并在实例化过程中调用父类构造函数。在Python中,我们使用 super 来实现这一点,这非常好。
我想做相反的事情:我有一个父类,它是一些子类的模板。然后我希望每个子类都有一个函数,允许实例克隆自身。
class Parent(object):
    def __init__(self, ctype, a):
        print('This is the parent constructor')
        self._ctype = ctype
        self._a = a

    @property
    def a(self):
        return self._a

    @property
    def ctype(self):
        return self._ctype


class ChildOne(Parent):
    def __init__(self, a):
        super(ChildOne, self).__init__('one', a)
        print('This is the child One constructor')
        self.one = 1

    def clone(self):
        return ChildOne(self._a)


class ChildTwo(Parent):
    def __init__(self, a):
        super(ChildTwo, self).__init__('two', a)
        print('This is the child Two constructor')
        self.two = 2

    def clone(self):
        return ChildTwo(self._a)

现在,如果我创建一个子类的实例,我可以将其克隆:
>>> k = ChildOne(42)
>>> k.ctype
'one'
>>> l = k.clone()
>>> l.a
42
>>> l is k
False

问题在于,clone方法在两个子类中都有重复的实现,而且几乎是一模一样的,唯一不同的是我需要明确指定调用哪个构造函数。是否可能设计一个在父类中定义的clone方法,能够正确地继承到子类中?
1个回答

4
可以使用以下方法来实现:
代码:

代码:

class Parent(object):

    def clone(self):
        return type(self)(self._a)

测试代码:

class Parent(object):
    def __init__(self, ctype, a):
        print('This is the parent constructor')
        self._ctype = ctype
        self._a = a

    @property
    def a(self):
        return self._a

    @property
    def ctype(self):
        return self._ctype

    def clone(self):
        return type(self)(self._a)


class ChildOne(Parent):
    def __init__(self, a):
        super(ChildOne, self).__init__('one', a)
        print('This is the child One constructor')
        self.one = 1

class ChildTwo(Parent):
    def __init__(self, a):
        super(ChildTwo, self).__init__('two', a)
        print('This is the child Two constructor')
        self.two = 2

k = ChildOne(42)
print(k.ctype)
l = k.clone()
print(l.a)
print(type(l))

结果:

This is the parent constructor
This is the child One constructor
one
This is the parent constructor
This is the child One constructor
42
<class '__main__.ChildOne'>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接