class object's attribute is also the instance's attribute?

Marco Nawijn nawijn at gmail.com
Thu Aug 30 08:34:51 EDT 2012


On Thursday, August 30, 2012 12:55:25 PM UTC+2, 陈伟 wrote:
> when i write code like this:
> 
> 
> 
> class A(object):
> 
>      
> 
>     d = 'it is a doc.'
> 
>     
> 
> 
> 
> t = A()
> 
> 
> 
> print t.__class__.d
> 
> print t.d
> 
> 
> 
> the output is same.
> 
> 
> 
> so it means class object's attribute is also the instance's attribute. is it right? i can not understand it.

I think the best way is to think of it as a global attribute restricted to the class A. Note that you even don't need an instance to get the value of the attribute. You can directly get it from the class itself.

>>> class A(object): d = 'my attribute'
>>> A.d
'my attribute'
>>> aobj = A()
>>> aobj.d
'my attribute'

Note that if you change 'd' it will change for all instances!
>>> bobj = A()
>>> bobj.d
'my attribute'

>>> A.d = 'oops...attribute changed'
>>> aobj.d
'oops...attribute changed'

>>> bobj.d
'oops...attribute changed'

If you want attributes to be local to the instance, you have to define them in the __init__ section of the class like this:

class A(object):

   def __init__(self):
        d = 'my attribute'

>>> aobj = A()
>>> bobj = A()

>>> aobj.d
'my attribute'

>>> bobj.d
'my attribute'

>>> aobj.d = 'oops...attribute changed'

>>> aobj.d
'oops...attribute changed'

>>> bobj.d
'my attribute'

Regards,

Marco



More information about the Python-list mailing list