【问题标题】:How to call child constructor from parent?如何从父级调用子构造函数?
【发布时间】:2017-09-28 13:59:40
【问题描述】:

在继承中,大多数时候我们希望创建从父类继承的子类,而在实例化的过程中又要调用父类的构造函数。在 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 方法,正确继承给子类?

【问题讨论】:

    标签: python oop inheritance constructor


    【解决方案1】:

    这可以通过:

    代码:

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

    【讨论】:

      猜你喜欢
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多