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
- #!/usr/bin/env python3
- class Test:
- def __init__(self):
- pass
- def add(self, a, b):
- return a + b
- def sub(self, a, b):
- return a - b
- to = Test()
- to_methods = [method for method in dir(to) if callable(getattr(to, method))]
- for m in to_methods:
- print("{}".format(m))
I discovered it at this site, hopefully that should provide some further detail!
沒有留言:
張貼留言