开发者

Python: Find out what method on derived class called base class method

Hope the title isn't to confusing wasn't sure how I should put it. I wonder if it's possible for the base class to know which method of the derived class called one开发者_Python百科 of it's methods.

Example:

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')

So is it possible for the output method to know which method from the Public class called it?


There is a somewhat magical way to do what you are looking for using introspection on the call stack. But that isn't portable since not all implementations of Python have the necessary functions. It's probably not a good design decision to use introspection either.

Better, I think, to be explicit:

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)

PS. Note that you have self.output as both a dict and a method. I've altered it so self._output is a dict, and self.output is the method.

PPS. Just to show you what I was referring to by magical introspection:

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


Have a look at the inspect module.

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

where method_that_called_me will be a string. The 1 is for the direct caller, the 3 the position of the function name in the 'frame record'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜