To use reflection in Python, it's a good idea to remember the following built-in functions.
#Returns whether object has an attribute of name
hasattr(object, name)
#Returns the name attribute in object. default can specify the value to be returned if there is no name attribute
getattr(object, name[, default])
#Returns True if object is callable. If True, object()Can be executed with.
callable(object)
#Attempts to return a list of valid attributes from object
dir([object])
The usage is like this. For example, if you want to either get the value of an attribute and return it, or execute a method and return it.
if hasattr(object, name):
attr = getattr(object, name)
if callable(attr):
return attr()
else:
return attr
Recommended Posts