I would like to add all methods of a class to a list so I can use them to call those methods from that list. I have tried inspect.getmembers(class)
, but I don't know how I would use it to call a function or subclass
Assuming you have a class Abc
:
class Abc:
def user_function(arg):
print(arg)
You can get all it's methods with dir(Abc)
. By calling it, you will get magic methods as well ( __init__
, __str__
and so on). So you can filter it like that:
methods_names = [method for method in dir(Abc) if not method.startswith('__')]
If you want to call it, you can use getattr
:
first_method = getattr(Abc, methods_names[0])
Note that first_method
will expect two arguments: self
and arg
, where self
can be an instance of Abc
class. So:
instance = Abc()
first_method(instance, 'Hello world')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.