On Sat, Apr 05, 2003 at 11:32:08AM -0800, Dylan Reinhardt wrote:
class Foo(base_classes): def __init__(self): # avoid doing stuff here pass
# add the following to a class with existing instances birthday = 0
def set_birthday(self): self.birthday = time.time()
def show_birthday(self): return self.birthday
-----
Now all existing instances will *immediately* have access to a birthday attribute, since it is a class variable. The moment you assign to self.birthday, a new variable is created that is local to that instance.
True, and I've used this idiom quite a bit... BUT I must warn any python newbies following this discussion that you can't use the same trick when modifying mutable attributes. You need to be sure to reassign the attribute, not just modify it in place. If you do the latter you'll just modify the class attribute and all instances will see the modification. Example:
class Foo: ... immutable = 0 ... mutable = [0, 1, 2] ... x = Foo() y = Foo() # now let's change y ... y.immutable = "not the original" # now let's examine them ... x.immutable 0 y.immutable 'not the original' # so far so good. what about the list? ... y.mutable[0] = "also not the original" x.mutable ['also not the original', 1, 2] # oops! we've changed mutable[0] for ALL instances.
-- Paul Winkler http://www.slinkp.com Look! Up in the sky! It's THE PAINTED FANG! (random hero from isometric.spaceninja.com)