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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With