python - 如何从父调用子构造函数?

标签 python oop inheritance constructor

在继承中,很多时候我们希望创建继承自父类的子类,而在实例化的过程中又不得不调用父类的构造函数。在 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)

现在,如果我创建其中一个 child 的实例,我可以克隆它:

>>> k = ChildOne(42)
>>> k.ctype
'one'
>>> l = k.clone()
>>> l.a
42
>>> l is k
False

问题是,clone 方法在两个子类中重复出现,而且几乎完全相同,只是我需要明确指定要调用的构造函数。是否可以设计一个我在父类中定义的 clone 方法,它可以正确地继承给子类?

最佳答案

这可以通过以下方式完成:

代码:

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'>

关于python - 如何从父调用子构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43714269/

相关文章:

c++ - 当从父类(super class)的指针调用时,基类函数不会覆盖父类(super class)函数

python - 修改python中的softmax函数库

javascript - 为什么 OOP 中需要工厂函数?

python - 为什么 sortBy() 无法在 Spark 中对数据进行均匀排序?

java - 数据库保存后是否真的有必要从事务中返回保存的实体?

javascript - JavaScript 对象创建方法有什么区别?

c++(构造函数)继承-LNK 2019错误

java - 使用 Java 中的组合和接口(interface)进行设计

python - Django get_initial 基于类的 View 方法不起作用

python - 将 Sentinel-1 SAR 图像的地理坐标(经度、纬度)转换为像素位置(x、y)