2017年8月20日 星期日

[ Python 常見問題 ] Finding what methods an object has

Source From Here 
Question 
Given a Python object of any kind, is there an easy way to get a list of all methods that this object has? 

How-To 
It appears you can use below code (callable/getattr): 
- test.py 
  1. #!/usr/bin/env python3  
  2.   
  3. class Test:  
  4.     def __init__(self):  
  5.         pass  
  6.   
  7.     def add(self, a, b):  
  8.         return a + b  
  9.   
  10.     def sub(self, a, b):  
  11.         return a - b  
  12.   
  13.   
  14. to = Test()  
  15. to_methods = [method for method in dir(to) if callable(getattr(to, method))]  
  16. for m in to_methods:  
  17.     print("{}".format(m))  
Execution output: 
# ./test.py
__class__
__delattr__
__dir__
__eq__
__format__
__ge__
...
__sizeof__
__str__
__subclasshook__
add
sub

I discovered it at this site, hopefully that should provide some further detail!

沒有留言:

張貼留言

[ Python 常見問題 ] Get all object attributes in Python?

Source From  Here   Question   Is there a way to  get all attributes/methods/fields/etc. of an object in Python ?  vars()  is close to what ...