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

Class Inheritance

If i have the following two classes:

class C1(object):
     x = 2
     y = 3

class C2(C1):
     x = 4
     w = 1

and i set instance = C2() and I ask for the attribute 'y' of instance_one by typing the command instance.y then I receive 3 as I would expect because class C2 inherits everything from class C1. However, if I have the following two classes:

class C1(object):
     def __init__(self):
          self.x = 2
          self.y = 3

class C2(C1):
     def __init__(self):
          self.x = 4
          self.w = 1

and i set instance_one = C2() and I ask for the attribute 'y' of instance by typing the command instance.y then I receive an error!!!!!

Why? what is it about init that makes this happen?

1 Answer

With your second example you're dealing with instance variables instead of class variables. In order to bind the remaining variables you could call the parent classes __init__:

class C2(C1):
  def __init__(self):
    super().__init__()
    self.x = 4
    self.w = 1

Now when you create an instance of C2 you'll get this if you output all the variables:

x: 4
y: 3
w: 1

Thank you. Did you mean to say "Now when you create an instance of C2''? (not a class of C2)

Good catch. I've fixed the original answer.