如何查找Python类的可调用属性?现有查询代码未输出预期结果原因是什么
代码问题分析
dir()函数返回的所有元素都是字符串格式的属性名称,而非属性对象本身。你直接对字符串执行callable()判断,返回结果永远是False,所以不会有任何符合条件的内容输出。
正确查找可调用属性的方法
你需要先用getattr()方法从实例中取出属性名对应的实际属性对象,再执行可调用判断,示例代码如下:
sample_list = [] for attr_name in dir(sample_list): attr_obj = getattr(sample_list, attr_name) if callable(attr_obj): print(attr_name)
如果需要过滤掉Python内置的双下划线开头/结尾的魔术方法,只输出普通可调用方法,可以增加一层判断逻辑:
sample_list = [] for attr_name in dir(sample_list): # 过滤系统内置魔术方法 if attr_name.startswith('__') and attr_name.endswith('__'): continue attr_obj = getattr(sample_list, attr_name) if callable(attr_obj): print(attr_name)
运行修改后的代码即可输出append、pop、insert等你预期的列表可调用属性。
内容的提问来源于stack exchange,提问作者Ser.T
相关产品推荐
相关产品推荐

