Reputation: 2414
I am trying to learn Classes and Subclasses. So, I started with this…
class Class1:
def __init__(self, name):
self.name = name
self.valx = "With Class1"
def __repr__(self):
return "Result: %s - %s " % (self.name, self.valx)
option1 = Class1("Paul")
print(option1)
Result: Paul - With Class1
But now, I want to work with a Subclass and set the value of valx to With Class1 or With Class2 in relation to Class or Subclass.
I want to reach or obtain this
option1 = Class1("Paul")
print(option1)
Result: Paul - With Class1
option2 = Class2("Paul")
print(option2)
Result: Paul - With Class2
My idea was to add
class Class2(Class1):
self.valx = "With Class2"
But I doesn´t work and I´m trying all what my mind can without results. Anyone can help me?
Remember that I´m learning! Happy Holidays!
Upvotes: 2
Views: 60
Reputation: 42788
You have to overwrite the __init__
method in Class2
:
class Class2(Class1):
def __init__(self, name):
super().__init__(name) # call __init__ of super class
self.valx = "With Class2"
Upvotes: 2