list/classmethod problems

Magnus Lycka lycka at carmen.se
Wed Mar 15 13:40:45 EST 2006


ahart wrote:
> I thank you all for your help and suggestions. I wasn't aware that
> default values were considered class (static) values. That seems a
> little odd to me, but as long as I know that's the case, I'll be fine.

It's all very simple and regular: Things in the class scope
is shared between all instances of the class. This applies to
both __text, __get_text, __set_text, text and __init__ in the
Item class. All these things are shared, since they are defined
in the scope of the class. That's the namespace where they
exists, not the instance. The typical thing to put in the class
scope is obviously methods, although some plain data can belong
there too.

When you access something in the instance, e.g. self.__text,
where self is an Item instance, it will follow a certain lookup
procedure. If it finds __text in the instance, it will use that
object. If not, it will look in the scope of the class, and if
it's not found there, it will look in base classes of Item and
so on.

This means that __get_text will find Item.__text if __text does
not exist in the instance object. On the other hand, when you
assign to self.__text in __set_text, you will get a new name
__text in the instance, and the next __get_item call will find
a __text in the instance, not the shared in the class scope.

Assignments in Python means "make this name refer to that object".
As far as I understand, that's like Java if you don't use those
half-life types like int that aren't proper objects. So, it does
never mean "copy a value to this location in memory" as it does
in C / C++.

With the list in Parent, you never make any assignment, so
there will never be any __item in the instance namespace. All
self.__items lookups will end up in the class namespace.

Since lists are mutable, you can change this list object, and
the changes will be visible to all instance. With the __text
attribute in Item, which is a string (immutable) there is no
way to change the value. To get a new __text value in the
class scope, you'd have to do self.__class__.__text = ... or
Item.__text = ..., and I doubt that you would do that by
accident! ;^)

What made you try to put your private attributes in the class
scope instead of putting them in __init__? Perhaps it's hard
to entirely give up the idea of somehow declaring your class
attributes even if there is no such things as variable
declarations in Python. :)




More information about the Python-list mailing list