Overriding a method at the instance level on a subclass of a builtin type
Arnaud Delobelle
arnodel at googlemail.com
Thu Dec 4 12:31:46 EST 2008
"Zac Burns" <zac256 at gmail.com> writes:
> The class method seems to be the most promising, however I have more
> 'state' methods to worry about so I might end up building new classes
> on the fly rather than have a class per permutation of states! Now the
> code isn't quite as clear as I thought it was going to be.
>
> It seems unfortunate to me that methods are always looked up on the
> class for new style objects. Was this done for speed reasons?
It's only special methods such as __getitem__, ...
You can override normal method on a per-object basis just by adding a
callable attribute with its name to the object:
>>> class A(object):
... def foo(self): print 'A.foo'
...
>>> a = A()
>>> a.foo()
A.foo
>>> def a_foo(): print 'a.foo'
...
>>> a.foo = a_foo
>>> a.foo()
a.foo
--
Arnaud
More information about the Python-list
mailing list