Để gọi một hàm khi chỉ có tên hàm dưới dạng chuỗi, sử dụng hàm built-in getattr().
Cú pháp
import module_name
func = getattr(module_name, 'function_name')
result = func()
Ví dụ
import fibo
result = getattr(fibo, 'baz')
print(result)
Áp dụng rộng hơn
getattr() hoạt động với:
- Module-level functions
- Class methods
- Instance methods
- Class attributes
Ví dụ với class
class MyClass:
def hello(self):
return "Hello!"
obj = MyClass()
method = getattr(obj, 'hello')
print(method()) # Hello!
Lưu ý: Nên kiểm tra sự tồn tại bằng hasattr() trước khi gọi để tránh AttributeError.