3
class MyClass:
  def my_method(self):
    print(get_context())

MyClass().my_method()

I need get next line:

MyClass::my_method

sys._getframe(2).f_code.co_name gives me only "my_method". How to get also class name?

Artem Selivanov
  • 1,867
  • 1
  • 27
  • 45

1 Answers1

1

You can get your classname by calling __class__.__name__ from self.

class Foo(object):
    def bar(self):
        print(self.__class__.__name__)

Foo().bar()

Output: Foo

idjaw
  • 25,487
  • 7
  • 64
  • 83
  • No. The get_context() function does not knows about "self" – Artem Selivanov Feb 06 '16 at 20:59
  • What are you trying to do? Do you have control over that method? Can you pass parameters to that method? You *could* pass "self" to the method and you will have the information you need as well? – idjaw Feb 06 '16 at 21:09
  • 1
    Take a look at this. I think this is what you are looking for: http://stackoverflow.com/questions/17065086/how-to-get-the-caller-class-name-inside-a-function-of-another-class-in-python – idjaw Feb 06 '16 at 21:17
  • I took out the `B` method from the class on its own and it worked. That should be it I believe. – idjaw Feb 06 '16 at 21:19
  • This is necessary for debug purposes with simple syntax: for example: INFO_MSG("Hi!") >> MyClass::MyMethod INFO: Hi! Thaks! Answer above helped me. – Artem Selivanov Feb 07 '16 at 06:48