繁体   English   中英

Python:如何在子 class 初始化时继承父 class 的所有当前属性?

[英]Python: How to in inherit all current attributes of parent class at time of child class initialization?

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

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

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)

想法?

更新您的孩子 class 定义:

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

当您的程序运行时,output 为6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM