Overriding __setattr__ in classes requires care when setting attributes yourself. Here's an idea for safely setting attributes in __init__.
Update: this idea doesn't work. See Mike Foord's recipe for one that does:
Python, 12 lines
1 2 3 4 5 6 7 8 9 10 11 12
class MyClass(object): def __init__(self, foo, bar): # set attributes normally here self.foo = foo self.bar = bar # override __setattr__ # NOTE: doesn't really work, __setattr_impl won't be called. self.__setattr__ = self.__setattr_impl def __setattr_impl(self, name, value): pass # definition goes here
For different approach to the same issue, see Mike Foord's recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389916
doesn't work :(. __setattr__ will only work if it exists at the class level.
here's a snapshot:
"blah" isn't printed...
(sup dude? i'm bored, i know... i'm telling you, down with types and classes. we don't need them. go antitype! :)
new-style. There's a good chance this would work with old-style classes (haven't tested though). New-style classes are more picky about magic methods being in the class.
My mistake. This doesn't seem to work in new-style _or_ old-style classes. I don't know why I thought it did work.