1
class C2:
  x = 2
  z = 2

class C3:
  w = 3
  z = 3

  def __init__(self):
    self.w += 1

class C1(C2, C3):
  x = 1
  y = 1

I1 = C1()
I1.name = 'I1'

I2 = C1()
I2.name = 'I2'

print I1.w  # 4
print I2.w  # 4
print C3.w  # 3

Can you explain me the results from last 3 prints? I can't find the logic in this :)

3
  • 1
    You already use the term class variables versus instance variables... C3 is a class, but I1 and I2 are instances.. I am not sure what the confusion is about here? Commented Aug 14, 2013 at 13:50
  • 2
    Assigning to self.<attribute name> always will create an instance attribute if there was none before. Reading an instance attribute where there is none will always fall through to the class to see if it is defined there. So self.w + 1 returns the sum of the class attribute w, then self.w = assigns that to the instance attribute w. Commented Aug 14, 2013 at 13:51
  • Thank you very much Martijn Pieters Commented Aug 14, 2013 at 13:59

2 Answers 2

2

I'm not sure how self.w += 1 will create an instance variables instead of just increment class variable or raise an exception for missing instance variable?

This might help you understand it:

>>> class Foo:
...  x = 1
...  def __init__(self):
...   print 'self =', self
...   print 'self x =', self.x
...   print 'foo x =', Foo.x
...   print self.x is Foo.x
...   Foo.x = 2
...   self.x = 3
...   print 'self x =', self.x
...   print 'foo x =', Foo.x
... 
>>> a = Foo()
self = <__main__.Foo instance at 0x1957c68>
self x = 1
foo x = 1
True
self x = 2
foo x = 3
>>> print a
<__main__.Foo instance at 0x1957c68>
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure what you're confused about. C3 defines an __init__ method that increases the value of self.w. So, both instances will get instance variables with a value of 4, whereas the class object itself has a class variable with the value of 3.

2 Comments

I'm not sure how self.w += 1 will create an instance variables instead of just increment class variable or raise an exception for missing instance variable?
@ju. Because you declared it. I edited my answer with an example of that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.