method = Klass.othermethod considered PITA

Steven Bethard steven.bethard at
Sun Jun 5 01:36:57 CEST 2005

John J. Lee wrote:
> It seems nice to do this
> class Klass:
>     def _makeLoudNoise(self, *blah):
>         ...
>     woof = _makeLoudNoise

Out of curiosity, why do you want to do this?

> 1. In derived classes, inheritance doesn't work right:
>>>>class A:
> ...  def foo(s):print 'foo'
> ...  bar = foo
> ...
>>>>class B(A):
> ...  def foo(s):print 'moo'
> ...
>>>>b = B()
> foo

Depends on what you mean by "work right".  It does do what you asked it 
to do.  You asked class A to store the "foo" object under the name 
"bar".  When you create an instance of B, and ask for the "bar" 
attribute, it isn't found in class B, so Python looks to the parent 
class.  The parent class, A, does have an object named "bar", so Python 
returns that.  And that object is the same object that you asked be 
named bar, namely the "foo" function.

If you want "bar" to be a function that *calls* the "foo" function, 
declare it as such:

py> class A(object):
...     def foo(self):
...         print 'foo'
...     def bar(self):
...         return
py> class B(A):
...     def foo(self):
...         print 'moo'
py> B().bar()

> 2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do
>    this.

In Python 2.4:

py> class A(object):
...     def foo(self):
...         print 'foo'
...     bar = foo
py> import pickle
py> pickle.loads(pickle.dumps(A)).bar
<unbound method>
py> pickle.loads(pickle.dumps(A())).bar()

Or maybe I misunderstand you?


More information about the Python-list mailing list