首页 > 解决方案 > 如何将类的每个属性调用到其继承的类

问题描述

假设我有一堂课:

class Base:
   def __init__(self, t1, t2, t3, t4, t5, ...):
       self.t1 = t1
       self.t2 = t2
       self.t3 = t3
       self.t4 = t4
       self.t5 = t5
       ...

class Derived(Base):
    def __init__(self, arg1, arg2, arg3, base_obj):
        super(Derived, self).__init__(t1 = base_obj.t1, t2 = base_obj.t2, t3 = base_obj.t3, ...)
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

base_obj1 = Base(1,2,3,4,5,...)
derived_obj1 = Derived('arg1', 'arg2', 'arg3', base_obj1)

如您所见Base,有很多属性,我Derived一个接一个地继承它们,这很难做到,有没有办法像我一样做这样的事情

super(Derived, self).__init__(self = base_obj)

所以我不必手动继承Basein 的每个属性Derived

标签: pythonclassinheritance

解决方案


我建议Base该类有一个方法可以为您选择正确的属性:

class Base:
    def __init__(self, t1, t2, t3, t4, t5, ...):
       self.t1 = t1
       self.t2 = t2
       self.t3 = t3
       self.t4 = t4
       self.t5 = t5
       ...

    #Base should know which attributes are created in __init__()
    #so this method just has to be kept in sync
    def pick_init_attributes(self):
        return (self.t1, self.t2, self.t3, ...)

class Derived(Base):
    def __init__(self, arg1, arg2, arg3, base_obj):
        super().__init__(*base_obj.pick_init_attributes())
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

base_obj1 = Base(1,2,3,4,5,...)
derived_obj1 = Derived('arg1', 'arg2', 'arg3', base_obj1)

此外,在编写时:class Derived2(Base):您只需要复制/粘贴该super()...行,而无需检查它是否具有正确的属性。


推荐阅读