简体   繁体   中英

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

I am attempting to utilize a child class within a parent class (wonky, I know) and want to inherit all parent attributes at the time of initialization into the child class. The general makeup looks something like the below.

I haven't been able to figure out how to inherit the attributes at the time of inheritance and not just the parentclass initialization (aka super(). init ()). Do I have to pass these updated values (like self.attr below) as parameters into the new child class or is there a cleaner way? I have a lot of attributes I want to pass, so I would prefer not to have to pass them as new attributes to the child 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)

Thoughts?

Update your child class definition:

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

When your program is run, the output is 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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