答案:在Python3中查看类的函数可用dir()或inspect模块。1. 使用dir()结合types.FunctionType筛选出函数;2. 用inspect.getmembers()配合inspect.isfunction获取更精确结果;3. 可进一步过滤仅保留自定义方法,排除内置或静态方法。推荐inspect用于复杂场景,dir()适合简单需求。

在 Python3 中查看类中有哪些函数,可以通过几种方式实现。最常用的是使用内置函数 dir() 或 inspect 模块来获取类的方法列表。
使用 dir() 查看类的属性和方法
dir() 可以列出类的所有属性和方法,包括继承的和内置的。你可以从中筛选出函数:
class MyClass:
def method_a(self):
pass
def method_b(self):
pass
x = 100查看类中的所有成员
print(dir(MyClass))
输出会包含很多内置属性(如 __init__),你可以通过判断是否为函数来过滤:
立即学习“Python免费学习笔记(深入)”;
import typesmethods = [attr for attr in dir(MyClass) if isinstance(getattr(MyClass, attr), types.FunctionType)] print(methods)
使用 inspect 模块更精确地查找方法
inspect 模块提供了更专业的工具来检查类结构,推荐使用 inspect.getmembers() 配合 inspect.isfunction() 或 inspect.ismethod():
import inspectclass MyClass: def method_a(self): pass
def method_b(self): pass @staticmethod def static_method(): pass @classmethod def class_method(cls): pass获取所有是函数的成员
functions = inspect.getmembers(MyClass, predicate=inspect.isfunction) print("普通函数和方法:", [name for name, _ in functions])
如果只想看实例方法,可以进一步筛选
instancemethods = [ name for name, func in inspect.getmembers(MyClass, inspect.isfunction) if not func.qualname.startswith('MyClass.class') and not func.name == 'static_method' ] print("实例方法:", instance_methods)
只查看用户定义的方法(排除内置)
如果你只想看自己写的函数,排除像 __init__ 这样的双下划线方法,可以加一个过滤条件:
custom_methods = [name for name, func in inspect.getmembers(MyClass, inspect.isfunction)
if not name.startswith('__')]
print("自定义方法:", custom_methods)
基本上就这些常用方式。用 inspect 更准确,适合写工具或调试;简单场景用 dir() 加类型判断也够用。










