A summary of reflection methods such as dynamically creating an instance in Python, acquiring a method and calling it.
If you want to dynamically create an instance from a character string etc. in Python, do as follows.
mod = __import__("exceptions",fromlist=["Exception"])
class_def = getattr(mod,"Exception")
obj = class_def("message") # obj = Exception('message',)
The leading __import__
corresponds to the import declaration (in the above example, it has the same meaning as executing from exceptions import Exception
. It is not necessary to explicitly read exceptions. It is just an example. Is).
Get the class definition of the corresponding class by getattr
from this module, and finally create an object using it.
Reference
How to dynamically load a Python class
Use inspect to get the definition of the class including the method.
ʻInspect.getmembers gets the definition,
getattrgets the definition from the object, and then executes it. Of course, you can call
getattr` directly if the method name has a hit in advance.
upper_method = filter(lambda f: f[0] == "upper", inspect.getmembers("String",inspect.isroutine))[0]
invoker = getattr("abc",upper_method[0])
invoker() # 'ABC'
It's natural that I want to take only the ones with decorators, but at the moment [very muddy methods](http://stackoverflow.com/questions/5910703/howto-get-all-methods-of- It seems that there is only (a-python-class-with-given-decorator) (specifically, it feels like reading the source code and looking for the beginning @).
If you want to get all public properties (member variables), do as follows.
attributes = inspect.getmembers(self, lambda a: not(inspect.isroutine(a)))
filter(lambda a: not(a[0].startswith("__")), attributes)
Those that do not correspond to ʻisroutine = The member variables are extracted, and the ones whose names do not start with
__are extracted. To get the value from the obtained property, use
getattr` as well as the method.
Recommended Posts