I need to create a script that allows you to access object atributes dynamically from getattr()
built-in function, but I'm having lots of troubles when trying to access the object methods, here is an example:
class Dog():
def __init__(self):
self.age = 12
self.name = 'Bobby'
def eat(self):
print("I'm eating!")
If I then initialize the object and try to access their attributes:
mydog = Dog()
res = getattr(mydog, 'age')
print(res)
#--> return: 12
But if I try to access the eat
method:
mydog = Dog()
res = getattr(mydog, 'eat()')
print(res)
#--> return: AttributeError: 'Dog' object has no attribute 'eat()'
I have already tried to write the method name without quotation marks, and the best solution that I found is to write the method without the parentheses and then access the function from res
:
mydog = Dog()
res = getattr(mydog, 'eat')
res()
#--> return: I'm eating!
I could code a conditional that detects if res
contains a variable or a function and call it in case it's a method, but is there a better solution to this?