简体   繁体   中英

Default arguments in a child class and an inheritance (Python 3.10)

I want a child class to inherit from a parent class all methods and attributes with one small change - setting a default value for one argument in the child class shared with the parent class. How can I do it? With following code, I get an AttributeError when trying to call add method on the child class' instance.

https://pastebin.com/WFxmbyZD

def ParentClass():
    """An exemplary parent class."""
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
    def adder(self):
        return a + b
 
def ChildClass(ParentClass):
    """An exemplary child class."""
    def __init__(self, a, b=3):
        super().__init__(a, b)
 
 
child_class_instance = ChildClass(5)
print(child_class_instance.adder())

You have a mistake declaring the class.

I will show you examples here. The child class can have a different signature for the constructor and the methods.

class ParentClass:
    """An exemplary parent class."""

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def adder(self):
        return self.a + self.b

    def adder_bis(self, c):
        return self.a + self.b + c


class ChildClass(ParentClass):
    """An exemplary child class."""

    def __init__(self, a, b=3):
        super().__init__(a, b)

    def adder_bis(self):
        return super().adder_bis(self.a)


child_class_instance = ChildClass(5)
print(child_class_instance.adder())
print(child_class_instance.adder_bis())

I commented what I thought was wrong:

class ParentClass():                  #class instead of def
    """An exemplary parent class."""
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
    def adder(self):
        return self.a + self.b         #use self here
 
class ChildClass(ParentClass):         #class instead of def
    """An exemplary child class."""
    def __init__(self, a, b=3):
        super().__init__(a, b)
 
 
child_class_instance = ChildClass(5)
print(child_class_instance.adder())

output:

8

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