Reputation: 898
I have the following class:
class Math():
def double(self, x):
return 2*x
def triple(self, x):
return 3*x
Now, I want to get the list of methods defined in the class. I can do this in the following way:
method_list = [func for func in dir(Math) if callable(getattr(Math, func)) and not func.startswith("__")]
Now, I would like method_list
itself to be an object of the class Math. It doesn't work to simply define it (as it is now at least) inside the class. How can I do this?
Upvotes: 1
Views: 44
Reputation: 110756
class Math():
def double(self, x):
return 2*x
def triple(self, x):
return 3*x
@classmethod
def method_list(cls):
return [func for func in dir(cls) if callable(getattr(cls, func)) and not func.startswith("__") and func != "method_list"]
usage example at interactive session:
In [123]: Math.method_list()
Out[123]: ['double', 'triple']
Upvotes: 2
Reputation: 39422
You can use a decorator because the class must be fully defined for python to pass the class to the decorator.
def addMethods(cls):
method_list = [func for func in dir(cls) if callable(getattr(cls, func)) and not func.startswith("__")]
cls.method_list = method_list
return cls
@addMethods
class Math():
pass
Upvotes: 0