python reflection during runtime
Using Python reflection feature to discover properties and methods of an class
class Employee:
name: str
id: int
def __init__(self, ename:str, eid:int):
self.name = ename
self.id = eid
def hello(_self):
print("emplyoee")
@property
def email(self):
return "kepung@gmail.com"
e = Employee("Alice", 2)
List all methods and properties
print(dir(e))
['__annotations__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'email', 'hello', 'id', 'name']
Specific method using hasattr
# check if it has attribute
print(hasattr(e, "hello")) # return True
print(hasattr(e, "name")) # return True
print(hasattr(e, "hello_fake")) # return false
Get actual method or property using getattr
# using getattr to get actual method
hello_method = getattr(e, "hello")
if hello_method != None:
hello_method()
else:
print("method does not exist")
# output employee as it is being run
# Get all methods
methods = inspect.getmembers(e, predicate=inspect.ismethod)
for m in methods:
print(m)
# Get all properties
properties = [name for name, value in inspect.getmembers(type(e))
if isinstance(value, property)]
print("Properties:", properties)
Comments