Reflection in Python

A summary of reflection methods such as dynamically creating an instance in Python, acquiring a method and calling it.

Dynamic instantiation

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

Get method definition

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 callgetattr` 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 @).

Get property

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, usegetattr` as well as the method.

Recommended Posts

Reflection in Python
Reflection in Python
Quadtree in Python --2
Python in optimization
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Sorted list in Python
Daily AtCoder # 36 in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 18 in Python
Singleton pattern in Python
File operations in Python
Key input in Python
Daily AtCoder # 33 in Python
Logistic distribution in Python
Daily AtCoder # 7 in Python
LU decomposition in Python
One liner in Python
Daily AtCoder # 24 in Python
case class in python
RNN implementation in python
Daily AtCoder # 8 in Python
File processing in Python
Elasticsearch Reindex in Python
Daily AtCoder # 42 in Python
Basic sorting in Python
Http request in python