Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Having an issue.

I know this doesn't completely have to do with the lesson, but I need some help. I tried playing around with classes a bit, and for some reason when I try to change an inherited variable of a subclass, it wont work. Example:

class supClass:
     def __init__(self, **info):
        self.name = info.get("name", "...")
        self.age = info.get("age", 100)
class sub(supClass):
    age = 200

=-=-= Console =-=-=
p = sub()
p.age --> 100

The output is still 100. Please help. Sorry if this confused you.

2 Answers

Yeeka Yau
Yeeka Yau
7,410 Points

Not sure if this is exactly the right answer, as I haven't tried it myself, but I think this is occurring because you don't have a init method for your sub class. So when you create an object, it runs the init method from your supClass. If you create an init method in your sub class, I would imagine that would fix the problem.

sub inherits __init__ from supClass because it doesn't have its own, so it's called when p is created, effectively in the same scope. The reason p gets 100 instead of 200 is that when it's set in an __init__ procedure, it's object-level instead of class-level and so takes precedence.

Defining __init__ (and overriding the version that would otherwise be inherited) in the subclass gives you what you want.