Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This modified version of #2 might help clear things up. I've only added print statements. In general, when issues like this come up, printing the id()s of identifiers can help:

Edit: Added some extra blank lines because lines were getting joined together.

# class_variables.py

class A(object):

    x = 1
class B(A):

    pass
class C(A):

    pass
print "Initially, A.x, B.x, C.x and their ids:"

print A.x, B.x, C.x

print id(A.x), id(B.x), id(C.x)

B.x = 2

print "After B.x = 2, A.x, B.x, C.x and their ids:"

print A.x, B.x, C.x

print id(A.x), id(B.x), id(C.x)

A.x = 3

print "After A.x = 3, A.x, B.x, C.x and their ids:"

print A.x, B.x, C.x

print id(A.x), id(B.x), id(C.x)

And the output:

>python class_variables.py

Initially: A.x, B.x, C.x and their ids:

1 1 1

30519808 30519808 30519808

After B.x = 2: A.x, B.x, C.x and their ids:

1 2 1

30519808 30519796 30519808

After A.x = 3: A.x, B.x, C.x and their ids:

3 2 3

30519784 30519796 30519784



Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: