How can I programmatically find the name of a method from within that method?
Tony
aclarke11 at yahoo.co.uk
Wed Aug 8 19:41:46 EDT 2007
On Aug 8, 9:28 pm, Peter Otten <__pete... at web.de> wrote:
> No, just wrong.
>
> >> class A:
>
> ... def alpha(self): return dir(self)[-2]
> ... def gamma(self): return dir(self)[-1]
> ...>>> a = A()
> >>> a.alpha(), a.gamma()
> ('alpha', 'gamma')
> >>> a.beta = 42
> >>> a.alpha(), a.gamma()
>
> ('beta', 'gamma')
>
> Peter
Only wrong if the function is only to write its own name. if it does
something else as well, seems to work:
class a:
def square(self, x):
print 'executing:', dir(self)[-1]
print x*x
def cube(self, x):
print 'executing:', dir(self)[-2]
print x*x*x
b=a()
b.cube(4),b.square(2)
b.c =4
b.cube(3), b.cube(2)
executing: cube
64
executing: square
4
executing: cube
27
executing: cube
8
cheers
More information about the Python-list
mailing list