Self function

Duncan Booth duncan.booth at invalid.invalid
Tue May 5 22:19:54 CEST 2009


Aaron Brady <castironpi at gmail.com> wrote:

> Here is how to get the function into the function as an argument, and
> still permit recursive calls onto it.
> 
>>>> def auto( f ):
> ...     def _inner( *ar, **kw ):
> ...             return f( g, *ar, **kw )
> ...     g= _inner
> ...     return g
> ...
>>>> @auto
> ... def f( self, n ):
> ...     print( self, n )
> ...     return 1 if n== 1 else n* self( n- 1 )
> ...
>>>> f(7)
><function _inner at 0x00BA0D68> 7
><function _inner at 0x00BA0D68> 6
><function _inner at 0x00BA0D68> 5
><function _inner at 0x00BA0D68> 4
><function _inner at 0x00BA0D68> 3
><function _inner at 0x00BA0D68> 2
><function _inner at 0x00BA0D68> 1
> 5040
> 

It might be better to use some convention other than 'self' for the first 
argument otherwise it will cause confusion when writing recursive methods:

>>> class C(object):
	@auto
	def meth(this, self, n):
		print this, self, n
		return 1 if n==1 else n*this(self, n-1)

>>> inst = C()
>>> inst.meth(5)
<function _inner at 0x0000000003680198> <__main__.C object at 
0x000000000366C4E0> 5
<function _inner at 0x0000000003680198> <__main__.C object at 
0x000000000366C4E0> 4
<function _inner at 0x0000000003680198> <__main__.C object at 
0x000000000366C4E0> 3
<function _inner at 0x0000000003680198> <__main__.C object at 
0x000000000366C4E0> 2
<function _inner at 0x0000000003680198> <__main__.C object at 
0x000000000366C4E0> 1
120



More information about the Python-list mailing list