Steven Bethard <[EMAIL PROTECTED]> writes:

> 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?

I don't.  It's just a habit I picked up from the standard library.


> > 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()
> >>>>b.bar()
> > foo
> 
> Depends on what you mean by "work right".  It does do what you asked
> it to do.

Well, gee, I guess so!

By "right" simply meant "according to the intent of the people who
tend to write such code" (and I do hope you're not going to get
over-literal about *that* non-clinically-precise statement).  It's
obviously a tacit intent, though, hence the problem.


>  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.

Yes.  My point was simply that the simplicity of writing method2 =
method1 in a class body is an attractive nuisance.


> 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 self.foo()
> ...
> py> class B(A):
> ...     def foo(self):
> ...         print 'moo'
> ...
> py> B().bar()
> moo

It was my intent to push people to do that instead, yes.


> > 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 A.foo>
> py> pickle.loads(pickle.dumps(A())).bar()
> foo

I meant class instances.


John
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to