Style question - defining immutable class data members

Terry Reedy tjreedy at
Sat Mar 14 19:26:40 CET 2009

Maxim Khitrov wrote:
> On Sat, Mar 14, 2009 at 12:50 PM, MRAB <google at> wrote:
>> Maxim Khitrov wrote:
>>> Very simple question on the preferred coding style. I frequently write
>>> classes that have some data members initialized to immutable values.
>>> For example:
>>> class Test(object):
>>>    def __init__(self):
>>>        self.some_value = 0
>>>        self.another_value = None
>>> Similar effect can be achieved by defining some_value and
>>> another_value for the entire class, like so:
>>> class Test(object):
>>>    some_value = 0
>>>    another_value = None
>>> The advantage of doing this is that the assignments are evaluated once
>>> and thus the creation of that class is a bit faster. Access is still
>>> performed through self.some_value and self.another_value. Is there a
>>> reason to prefer the first style over the second?
>> In the first case each instance has its own attributes, whereas in the
>> second case the attributes belong to the class and are thus shared by
>> all the instances. Which you use depends on whether you want them shared
>> or not.
> When the types are immutable, there is no difference. The second case
> is faster and consumes less memory (initially), but nothing else
> changes. I'm simply asking if it is considered poor style to define
> data members for the class when they are only used by instances.

If they are class constants (the same for all instances, I would define 
them as such.  If duplicated for all instances in __init__, I would 
expect there to be methods that replace them.  I particular, I would 
expect that .some_value would possibly get a value other than 0.

More information about the Python-list mailing list