How to get the caller class name inside a function of another class in python?

前端 未结 6 799
花落未央
花落未央 2020-12-02 19:08

My objective is to stimulate a sequence diagram of an application for this I need the information about a caller and callee class names at runtime. I can successfully retrie

6条回答
  •  我在风中等你
    2020-12-02 19:30

    Using the answer from Python: How to retrieve class information from a 'frame' object?

    I get something like this...

    import inspect
    
    def get_class_from_frame(fr):
      args, _, _, value_dict = inspect.getargvalues(fr)
      # we check the first parameter for the frame function is
      # named 'self'
      if len(args) and args[0] == 'self':
        # in that case, 'self' will be referenced in value_dict
        instance = value_dict.get('self', None)
        if instance:
          # return its class
          return getattr(instance, '__class__', None)
      # return None otherwise
      return None
    
    
    class A(object):
    
        def Apple(self):
            print "Hello"
            b=B()
            b.Bad()
    
    class B(object):
    
        def Bad(self):
            print"dude"
            frame = inspect.stack()[1][0]
            print get_class_from_frame(frame)
    
    
    a=A()
    a.Apple()
    

    which gives me the following output:

    Hello
    dude
    
    

    clearly this returns a reference to the class itself. If you want the name of the class, you can get that from the __name__ attribute.

    Unfortunately, this won't work for class or static methods ...

提交回复
热议问题