defining a method inside of another method

dj trombley badzen at yifan.net
Fri Dec 17 02:21:01 EST 1999


Felix Thibault wrote:
> 
> This is probably a trivial question, but it's driving me crazy:
> 
> I have a class that has methods that look like this:
> 
> class Eggs:
>         def keep(self, inlist):
>                 keepers = filter(self.choose, inlist)
>                 mn = {}
>                 for name, stuff, idont, careabout in keepers:
>                         mn[name] = ()
>                 def mystacks(dict = mn):
>                         return dict.copy()
>                 self.stacker = mystacks
>                 return keepers
> 
> Both keep and stacker get called as self.keep(inlist) and self.stacker() in
> other methods, and they both work like they're supposed to. In keep, I have
> 2 names in the header, and self gets passed in as the first argument- but
> if self were being passed in as the first argument  to stacker wouldn't it
> overwrite dict and mess up mystacks ??? Where does it go? What am I missing?
> 
> Thanks!
> 
> Felix

Any time you call a method as an attribute of another object, the object
is applied as the first
argument to that method.  For example, I could define the following:

class foo:
   def __init__(self):
      self.bar = 5
   def add_my_bar(x,y):
      return (x.bar + y)

f = foo()
foo.add = f.add_my_bar

And then calling "f.add(6)" will return 11, for example.  However, a
function does not
have this behavior when it is called in the same way.  Simply assigning
the object to
an object attribute does not make it a method of that object.

The essential difference here is in what namespace the assignment
occurs.
If you use the variable passed as thefirst argument to a method,
(typically called "self")
then this assignment is to the dictionary of the instance.  If you use
the class object 
itself, then functions assigned become methods and behave in the
expected way; as if they
has been defined along with the class.

You can refer to the class being defined from within the class
definition by simply using
its name.

-dj

Dave Trombley
<badzen at yifan.net>



More information about the Python-list mailing list