python class attribute

Posted by chnet on Stack Overflow See other posts from Stack Overflow or by chnet
Published on 2010-05-27T18:00:14Z Indexed on 2010/05/27 18:11 UTC
Read the original article Hit count: 266

Filed under:
|
|

Hi, i have a question about class attribute in python.

class base :
    def __init__ (self):
        pass
    derived_val = 1

t1 = base()
t2 = base ()

t2.derived_val +=1
t2.__class__.derived_val +=2
print t2.derived_val             # its value is 2
print t2.__class__.derived_val   # its value is 3

The results are different. I also use id() function to find t2.derived_val and t2.class.derived_val have different memory address. My problem is derived_val is class attribute. Why it is different in above example? Is it because the instance of class copy its own derived_val beside the class attribute?

© Stack Overflow or respective owner

Related posts about python

Related posts about class