How can I programmatically find the name of a method from within that method?
Peter Otten
__peter__ at web.de
Wed Aug 8 16:28:59 EDT 2007
Tony wrote:
> Is this cheating?
Isn't it harder to calculate the magic indices than just writing down the
names twice?
> 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.square(3)
> b.cube(3)
> Output:
>
> PyMate r6780 running Python 2.3.5 (python)
> >>> function self naming2.py
>
> executing: square
> 9
> executing: cube
> 27
> Is this cheating?
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
More information about the Python-list
mailing list