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

前端 未结 6 812
花落未央
花落未央 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:18

    Perhaps this is breaking some Python programming protocol, but if Bad is always going to check the class of the caller, why not pass the caller's __class__ to it as part of the call?

    class A:
    
        def Apple(self):
            print "Hello"
            b=B()
            b.Bad(self.__class__)
    
    
    
    class B:
    
        def Bad(self, cls):
            print "dude"
            print "Calling class:", cls
    
    
    a=A()
    a.Apple()
    

    Result:

    Hello
    dude
    Calling class: __main__.A
    

    If this is bad form, and using inspect truly is the preferred way to get the caller's class, please explain why. I'm still learning about deeper Python concepts.

提交回复
热议问题