I wanted to do some handling of undefined methods or attributes calls in python class. Where if method is not present it is required to perform some task. Here in the example I have written some methods and some calls.
What I want to achieve is, if any call is not defined in the class, it goes to __getattr__
, and there I want to check if a method by the name "get_{the_called_method_or_attribute}" is present or not. If present just call the method and return its value.
I tried using dir
, self__dict__
and other, but none worked. It just called itself in recursion.
Is there any way to perform my query by not checking the existance of method or attribute in the call section rather inside the class?
class C:
def __init__(self, data):
self.data = data
def get_name(self):
return "{f_name} {l_name}".format(**self.data)
def get_f_name(self):
return data.get("f_name")
def get_l_name(self):
return data.get("l_name")
def get_email(self):
return data.get("email")
def access_undefined_methods(self, key):
return self.data.get(key, "Key '{}' does not present".format(key))
def __getattr__(self, name):
return self.access_undefined_methods(name)
data = {"f_name": "John", "l_name": "Doe", "email": "john@doe.com"}
obj = C(data)
print obj.get_name() # <-- John Doe
print obj.f_name # <-- John
print obj.l_name # <-- Doe
print obj.email # <-- john@doe.com
print obj.name # <-- this should execute obj.get_name()