将输出保存在数据结构中以便稍后检查。这些方法返回字符串(解析或选择 HTML,它们不会修改对象)。
我通过创建一个类找到了一个“硬编码”的解决方案,但目前还不太有动力:call list of function using list comprehension 。
[也许另一个用于检查库的库将是一个极端。我尝试在 Python 源代码中添加一些打印内容,但它不听我的。似乎另一个实例正在运行]
我已经尝试过这种语法(不可能):
result = [obj.f() for f in [append, attrs]]
因为 append
和 attrs
默认情况下不是静态函数,而是“点式”函数,如上所示。
目标只是简单检查所有 obj 方法。
[强烈建议进行编辑]
更新
In [122]: getattr? Docstring: getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. Type: builtin_function_or_method getattr(): attribute name must be string Only
2
works. It is the "result" to get (not hard-coding it) More information for 'model' as an object.
最佳答案
您需要任一绑定(bind)方法:
result = [f() for f in [obj.append, obj.attrs]]
或通过getattr
进行动态属性查找:
result = [getattr(obj, m)() for m in ["append", "attrs"]]
如果您计划对许多对象执行此操作,您可能需要使用operator.methodcaller
:
methods = [methodcaller(m) for m in ["append", "attrs"]]
results_for_obj_a = [f(obj_a) for f in methods]
results_for_obj_b = [f(obj_b) for f in methods]
# etc.
methodcaller
是一种从任何特定对象中抽象调用方法的想法的方法。
methodcaller(method_name)(obj) == getattr(obj, method_name)()
关于python - 将多个方法应用于单个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55838440/