On Dec 4, 12:31 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > "Zac Burns" <[EMAIL PROTECTED]> 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()
Note that the overriden "method" here is a plain function; it doesn't take self as the first argument. If you want to bind it to a callable that expects the first argument to be self, you have to bind explicitly self to the object: >>> def a_foo(self): print 'a.foo' >>> a.foo = a_foo >>> a.foo() TypeError: a_foo() takes exactly 1 argument (0 given) >>> from functools import partial >>> a.foo = partial(a_foo,a) >>> a.foo() a_foo George -- http://mail.python.org/mailman/listinfo/python-list