Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "wildcard method" in Python?

I am looking for a way to use a method of a class which is not defined in that class, but handled dynamically. What I would like to achieve, to take an example, is to move from

class Hello:
    def aaa(self, msg=""):
        print("{msg} aaa".format(msg=msg))

    def bbb(self, msg=""):
        print("{msg} bbb".format(msg=msg))

if __name__ == "__main__":
    h = Hello()
    h.aaa("hello")
    h.bbb("hello")

# hello aaa
# hello bbb

to the possibility of using aaa and bbb (and others) within the class without the need to define them explicitly. For the example above that would be a construction which receives the name of the method used (aaa for instance) and format a message accordingly.

In other other words, a "wildcard method" which would itself handle its name and perform conditional actions depending on the name. In pseudocode (to replicate the example above)

def *wildcard*(self, msg=""):
    method = __name__which__was__used__to__call__me__
    print("{msg} {method}".format(msg=msg, method=method))

Is such a construction possible?

like image 425
WoJ Avatar asked Apr 12 '16 13:04

WoJ


1 Answers

You could overload the class' __getattr__ method:

class Hello:
    def __getattr__(self, name):
        def f(msg=""):
            print("{} {}".format(msg, name))
        return f

if __name__ == "__main__":
    h = Hello()
    h.aaa("hello")
    h.bbb("hello")

Result:

hello aaa
hello bbb
like image 64
Kevin Avatar answered Oct 13 '22 21:10

Kevin