Reflection in Python

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

Reflection in Python
Reflection in Python
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
StepAIC in Python
N-gram 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
Daily AtCoder # 36 in Python
Clustering text in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
File operations in Python
Read DXF in python
Daily AtCoder # 53 in Python
Key input in Python
Use config.ini in Python
Solve ABC168D in Python
Daily AtCoder # 7 in Python
LU decomposition in Python
One liner in Python
Simple gRPC in Python
Daily AtCoder # 24 in Python
Solve ABC167-D in Python
Daily AtCoder # 37 in Python
case class in python