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

在 Python3 中查看类中有哪些函数,可以通过几种方式实现。最常用的是使用内置函数 dir() 或 inspect 模块来获取类的方法列表。
dir() 可以列出类的所有属性和方法,包括继承的和内置的。你可以从中筛选出函数:
class MyClass:
def method_a(self):
pass
<pre class='brush:python;toolbar:false;'>def method_b(self):
pass
x = 100print(dir(MyClass))
输出会包含很多内置属性(如 __init__),你可以通过判断是否为函数来过滤:
立即学习“Python免费学习笔记(深入)”;
import types <p>methods = [attr for attr in dir(MyClass) if isinstance(getattr(MyClass, attr), types.FunctionType)] print(methods)</p>
inspect 模块提供了更专业的工具来检查类结构,推荐使用 inspect.getmembers() 配合 inspect.isfunction() 或 inspect.ismethod():
import inspect
<p>class MyClass:
def method_a(self):
pass</p><pre class='brush:python;toolbar:false;'>def method_b(self):
pass
@staticmethod
def static_method():
pass
@classmethod
def class_method(cls):
passfunctions = 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() 加类型判断也够用。
以上就是查看类中函数的python3代码如何写?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号