2

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!

Daniel
42.8k4 gold badges57 silver badges82 bronze badges
asked Dec 24, 2015 at 18:04

1 Answer 1

2

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"
answered Dec 24, 2015 at 18:13
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Works great! I did not find that in the tutorials that I am following. Thanks and more. Happy Holidays!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.