python - 将多个方法应用于单个对象?

标签 python

将输出保存在数据结构中以便稍后检查。这些方法返回字符串(解析或选择 HTML,它们不会修改对象)。

我通过创建一个类找到了一个“硬编码”的解决方案,但目前还不太有动力:call list of function using list comprehension

[也许另一个用于检查库的库将是一个极端。我尝试在 Python 源代码中添加一些打印内容,但它不听我的。似乎另一个实例正在运行]

我已经尝试过这种语法(不可能):

result = [obj.f() for f in [append, attrs]] 

因为 appendattrs 默认情况下不是静态函数,而是“点式”函数,如上所示。

目标只是简单检查所有 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 enter image description here getattr(): attribute name must be string enter image description here Only 2 works. It is the "result" to get (not hard-coding it) enter image description here 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/

相关文章:

Python gpt-2-simple,一次加载多个模型

Python 获取特定角色的所有成员列表

python - 使用 numpy 对两个数组进行迭代操作

python - django 从 1.3 升级到 1.9 生成 TypeError : Item in `` from list'' not a string

c++ - C++ 中的嵌套字典/数组

python - 在 Keras 中将模型合并为一个

Python Plotly - 多个下拉图,每个都有子图

python - cv2.imshow() 给出黑屏

python - 查找每列的唯一值

python - 计算 360 度圆内的移动平均线