Style question - defining immutable class data members

David Stanek dstanek at dstanek.com
Sat Mar 14 15:25:37 EDT 2009


On Sat, Mar 14, 2009 at 12:32 PM, Maxim Khitrov <mkhitrov at gmail.com> 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 general I think it can be fine as long as you do use immutable
values. I use this pattern when I create data transfer objects[0].
Normally these objects don't have any methods. So you want to be
careful that you are doing it for the right reason. When I create
objects that are not DTOs I don't do this.

[0] http://martinfowler.com/eaaCatalog/dataTransferObject.html

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek



More information about the Python-list mailing list