defining a method inside of another method

Felix Thibault felixt at dicksonstreet.com
Sun Dec 19 23:30:37 EST 1999


At 07:21 12/17/99 GMT, dj trombley wrote:
>
>
>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

<snip!>

>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>
>-- 
>http://www.python.org/mailman/listinfo/python-list
>
>

OK, I think I get it now:

	If I define a function in a class's scope, it is called the way methods
are called, with the 	instance being passed in as the first argument.

	If I define a function in a method's scope and then bind it to an instance
variable, it's just
	an attribute which happens to be a function, and not a method. To make
stacker act like 	a method I would have to do something like:

		....
		def mystacks(dict=mn, self=self):
			try:
				self.stackcount = self.stackcount + 1
			except AttributeError:
				self.stackcount = 1
			return dict.copy()
		...

right?

Thanks!

Felix






More information about the Python-list mailing list