Style question - defining immutable class data members

Tim Wintle tim.wintle at teamrubber.com
Mon Mar 16 00:02:09 EDT 2009


On Sun, 2009-03-15 at 10:39 -0700, John Posner wrote:
> (My apologies if the thread has already covered this.) I believe I understand the WHAT in this situation, but I don't understand the WHY ...

> Is there a beneficial effect of silently creating the instance attribute, which outweighs the detrimental effects: (1) inconsistency, (2) the "surprising" decoupling?

>From an end-user point of view (rather than the point of accessing class
methods others mentioned), here are two more reasons:

1) To save memory - there's only one object stored, where an instance
variable will require the same memory every instance (normally)


2) referencing Zope objects (although any persistent object storage will
have the same argument):

(Zope is a web framework that stores data as instances of python classes
in a persistent database.)

let's say you have the class (missing all the boilerplate)

{{{
class ZMyUser():
    def __init__(self):
        self.lookuplanguage = {\
		"EN": "English"
		}
        self.language = "EN"

    def get_friendly_name(self):
        return self.lookuplanguage.get(self.language,"--")
}}}

And you create loads of these objects. But then you want to add French
as an option. How do you do that? All the objects have already been
created, so you could either: 

 * Run through every object in the database one by one and update the
dict as a one-off task (potentially taking a very long time as you force
the computer to pull the entire database off disk)

 * Have written  lookuplanguage as a class property, so re-initialising
the class will update the definition without any extra overhead.







More information about the Python-list mailing list