要获取一个类下面所有的方法,你可以使用Python的内置函数和属性。以下是一个示例,展示如何获取一个类及其所有子类中的所有方法:
```python
def get_all_methods(cls):
methods = []
for method in dir(cls):
if callable(getattr(cls, method)) and not method.startswith('__'):
methods.append(method)
return methods
示例类
class BaseClass:
def method1(self):
pass
def method2(self):
pass
def __init__(self):
pass
class DerivedClass(BaseClass):
def method3(self):
pass
获取BaseClass及其子类DerivedClass的所有方法
all_methods = get_all_methods(BaseClass)
print("Methods in BaseClass:", all_methods)
all_methods_derived = get_all_methods(DerivedClass)
print("Methods in DerivedClass:", all_methods_derived)
```
这段代码定义了一个`get_all_methods`函数,它接受一个类作为参数,并返回该类及其所有父类中定义的所有非魔法方法(即不以双下划线开头和结尾的方法)。然后,我们创建了两个类`BaseClass`和`DerivedClass`,并使用`get_all_methods`函数获取它们的方法列表。
请注意,这种方法会包括所有继承的方法,因此如果你只想获取当前类的直接方法,可以去掉`for method in dir(cls):`循环中的父类检查部分。