top | item 3281675 (no title) fakeempire | 14 years ago Excuse my ignorance, but why would that change all the instances in this case? I don't understand. Would you mind explaining more? discuss order hn newest pyre|14 years ago def __init__(self, ..., foo={}): self.foo = foo In this case, 'foo={}' is evaluated once, and returns a pointer to a dict(). After that, foo is always pointing to the same dict, not to a newly created empty dict.Run this in a Python interpreter: class PhoneBook(object): def __init__(self, names={}): self.names = names phonebook1 = PhoneBook() phonebook2 = PhoneBook() phonebook1.names['Bob'] = '+1 555 5555' print phonebook2.names['Bob'] The only thing that is really safe to put in the defaults are immutable values.
pyre|14 years ago def __init__(self, ..., foo={}): self.foo = foo In this case, 'foo={}' is evaluated once, and returns a pointer to a dict(). After that, foo is always pointing to the same dict, not to a newly created empty dict.Run this in a Python interpreter: class PhoneBook(object): def __init__(self, names={}): self.names = names phonebook1 = PhoneBook() phonebook2 = PhoneBook() phonebook1.names['Bob'] = '+1 555 5555' print phonebook2.names['Bob'] The only thing that is really safe to put in the defaults are immutable values.
pyre|14 years ago
Run this in a Python interpreter:
The only thing that is really safe to put in the defaults are immutable values.