On Thu, Dec 8, 2011 at 10:40 AM, Lie Ryan <lie.1...@gmail.com> wrote:

> On 12/09/2011 01:49 AM, rail shafigulin wrote:
>
>> i created a class and in some instances when i use it call some of its
>> methods i need to print a method name. the online search did produce
>> some results but none of them seem to work for me. for example one of
>> them said just to use __name__ or func_name but it didn't work for me.
>> i'm using python 3.1.1
>>
>>
> I'm guessing that you're  doing something like
>
> def foo():
>    ...
>
> print foo().__name__
>
> foo() would call the foo() function, so you'd be asking the .__name__ of
> the object returned by foo not the __name__ of foo. Instead you'd need to
> use the the function object itself, IOW don't call foo just do:
>
> print foo.__name__
>
>
> This should work for both python 2 and python 3, and for both class
> methods or regular functions.
>
>
> ______________________________**_________________
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>

as a matter of apology i found another way of getting a method name without
actually knowing the name of the method:

import inspect

class MyClass(object):
  def __init__(self):
    pass

  def mymethod(self):
    print(inspect.getframeinfo(inspect.currentframe()).function)

def main():
  a = MyClass()
  a.mymethod()

if __name__ == '__main__':
  main()
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to