Style question - defining immutable class data members
Gary Herron
gherron at islandtraining.com
Sat Mar 14 14:07:25 EDT 2009
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?
>
> - Max
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Such things are often called class attributes, and the are fine. If you
look through Python's standard library, you will find many examples of
class attributes.
However, you appear to have either a misuse or misconception of the word
"immutable' here. Whether the value you assign to a class attribute is
mutable or immutable is irrelevant. Also whether you plan on leaving
the value constant or not is also not relevant.
What does matter is this: If every instance wants access to a single
value (immutable or not), use a class attribute, otherwise use an
instance attribute.
Gary Herron
More information about the Python-list
mailing list