Re: How can I programmatically find the name of a method from within that method?



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
.



Relevant Pages

  • Re: PIC migration timing problem
    ... On the OSC2 pin both processors show a nice clock ... It's not executing the code twice speed, ... fewer instructions on 18Fxxx than 16Cxx and fewer instructions execute ...
    (comp.arch.embedded)
  • Re: PIC migration timing problem
    ... On the OSC2 pin both processors show a nice clock ... It's not executing the code twice speed, ... fewer instructions on 18Fxxx than 16Cxx and fewer instructions execute ...
    (comp.arch.embedded)
  • Re: PIC migration timing problem
    ... On the OSC2 pin both processors show a nice clock ... It's not executing the code twice speed, ... fewer instructions on 18Fxxx than 16Cxx and fewer instructions execute ...
    (comp.arch.embedded)
  • [std::getline] Avoid having to hit <Enter> twice, How to?
    ... When executing the above compiled code, I have to hit the key ... TWICE, once after entering my name, and another in a line all by ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Subreport Detail_Format being called twice
    ... >called from the Main report. ... (Loops through in the proper order, ... executing as many time as it needs to to do its job. ... twice or even more times. ...
    (microsoft.public.access.reports)