代码之家  ›  专栏  ›  技术社区  ›  Pickels

Python:找出派生类上称为基类方法的方法

  •  1
  • Pickels  · 技术社区  · 14 年前

    例子:

    class Controller(object):
        def __init__(self):
            self.output = {}
    
        def output(self, s):
            method_that_called_me = #is it possible?
            self.output[method_that_called_me] = s
    
    class Public(Controller):
        def about_us(self):
            self.output('Damn good coffee!')
    
        def contact(self):
            self.output('contact me')
    

    那么,output方法是否可能知道公共类中的哪个方法调用了它?

    2 回复  |  直到 14 年前
        1
  •  4
  •   unutbu    14 年前

    在调用堆栈上使用内省有一种神奇的方法来完成您想要的任务。但这并不是可移植的,因为并非所有Python实现都有必要的函数。使用内省也可能不是一个好的设计决策。

    我认为,最好是直截了当地说:

    class Controller(object):
        def __init__(self):
            self._output = {}
    
        def output(self, s, caller):
            method_that_called_me = caller.__name__
            self._output[method_that_called_me] = s
    
    class Public(Controller):
        def about_us(self):
            self.output('Damn good coffee!',self.about_us)
    
        def contact(self):
            self.output('contact me',self.contact)
    

    注意,你有 self.output 作为一个 dict method . 我把它改得很好 self._output 是一个 ,和

    PPS公司。只是想让你看看我所指的魔法内省:

    import traceback
    
    class Controller(object):
        def output_method(self, s):
            (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
            method_that_called_me = function_name
            self.output[method_that_called_me] = s
    
        2
  •  1
  •   Andre Holzner    14 年前

    inspect module .

    import inspect
    frame = inspect.currentframe()
    method_that_called_me = inspect.getouterframes(frame)[1][3]
    

    哪里 method_that_called_me 将是一个字符串。这个 1 3