class members vs instance members

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Jul 9 11:54:49 EDT 2006


hdixon a écrit :
> Ive spent a few days going thru a couple of Python tutorials. No
> problem until I got to classes. I guess my java mindset is blocking my
> vision. 

Then http://dirtsimple.org/2004/12/python-is-not-java.html

> I've borrowed another thread's code snippet and cannot explain
> the results:
> class MyClass:

  class MyClass(object):

>     list = []

This may not be too harmful in the given context, nut shadowing builtin 
types may not be a good idea.

>     myvar = 10
> 
>     def add(self, x):
>         self.list.append(x)

"list" is a class attribute. It's shared by all instances of MyClass. 
This is a FAQ AFAICT.

>         self.myvar = x

This creates an instance attribute named myvar that shadows the class 
attribute of the same name

(snip expected results)

> WHY do the "class members" list and myvar seem to behave differently?

cf above. And notice that in Python, binding (aka 'assignement') and 
name lookup on objects are different beasts. There have been quite a few 
threads about this recently.

> Given the way that list[] is supposedly shared why doesnt myvar exhibit
> the same behavior? 

Because binding to self.myvar creates the instance attribute "myvar". 
Notice that you have not rebound "list".

> It seems that myvar is acting like a true "instance
> member".

It is one.

> Is this simply because of the underlying types?

Nope, it's because in the first case (MyClass.list, accessed as 
self.list) you just call methods on the list object, which has no effect 
on the binding.



More information about the Python-list mailing list