【问题标题】:Python: How to in inherit all current attributes of parent class at time of child class initialization?Python:如何在子类初始化时继承父类的所有当前属性?
【发布时间】:2020-06-25 17:14:39
【问题描述】:

我正在尝试在父类中使用子类(我知道这很奇怪),并希望在初始化时将所有父属性继承到子类中。一般妆容如下所示。

我无法弄清楚在继承时如何继承属性,而不仅仅是父类初始化(又名 super().init())。我是否必须将这些更新的值(如下面的 self.attr)作为参数传递给新的子类,还是有更简洁的方法?我有很多要传递的属性,所以我不希望将它们作为新属性传递给子类)。

class ParentClass():
    def __init__(self, attr = None, attr1 = 1, attr2 = 2):
        
        self.attr = attr
        self.attr1 = attr1
        self.attr2 = attr2
    
    def define_attr(self):
        self.attr = self.attr1 + self.attr2
    
    def funct(self, val):
        
        if not self.attr:
            self.define_attr()
            
        part = ChildClass(val).do_thing()
        return part

class ChildClass(ParentClass):
    
    def __init__(self, val):
        self.val = val 
        
    def do_thing(self):
        thing = self.attr + self.val + 2 
        return thing
        
test = ParentClass()
result = test.funct(3)
print(result)

想法?

【问题讨论】:

    标签: python class parent-child


    【解决方案1】:

    更新您的子类定义:

    class ChildClass(ParentClass):
        
        def __init__(self, val):
            super().__init__(val)
            self.val = val 
            
        def do_thing(self):
            thing = self.attr + self.val + 2 
            return thing
    

    当你的程序运行时,输出是6

    【讨论】:

      猜你喜欢
      • 2014-06-20
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      相关资源
      最近更新 更多