Class Variable Access and Assignment

Magnus Lycka lycka at carmen.se
Fri Nov 4 18:28:54 EST 2005


Paul Rubin wrote:
> Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
> 
>>Follow the logical implications of this proposed behaviour.
>>
>>class Game:
>>    current_level = 1
>>    # by default, games start at level one  
> 
> 
> That's bogus.  Initialize the current level in the __init__ method
> where it belongs.

But there is a relevant use case for this:

If you have a class hierarchy, where the difference between the
classes is mainly/completely a matter of data, i.e. default
values. Then it's very convenient to use such defaults in the
class scope.

Of course, you *could* have an __init__ in the base class that
copies this data from class scope to instance scope on instance
creation, but why make it more complicated?

You could also imagine cases where you have many instances and
a big immutable variable which typically stays as default, but
must sometimes vary between instances.

As I explained in another post, member lookups in the instance
must look in the class to find methods, so why not get used to
the fact that it works like this, and use it when it's convenient.
It's not as if anyone puts a gun to your head and force you to
use this feature.



More information about the Python-list mailing list