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.
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())
CodePudding user response:
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())
CodePudding user response:
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