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

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

    Python 3.8

    import inspect
    
    
    class B:
        def __init__(self):
            if (parent := inspect.stack()[1][0].f_locals.get('self', None)) and isinstance(parent, A):
                parent.print_coin()
    
    
    class A:
        def __init__(self, coin):
            self.coin: str = coin
            B()
    
        def print_coin(self):
            print(f'Coin name: {self.coin}')
    
    
    A('Bitcoin')
    

提交回复
热议问题