首页 > 解决方案 > 迭代指定类的方法

问题描述

假设这样一个最小的 Mixin 组合了多个方法

class Mixin:
    "Iterate methods"
    def strip():
        return str.strip

    def title():
        return str.title

    def swapcase():
        return str.swapcase

处理一段文本的方法

content = "iterate methods  "
content = Mixin.strip()(content)
content = Mixin.title()(content)
content = Mixin.swapcase()(content)
print(content)

我将代码重构为:

ops = [Mixin.strip(), Mixin.title(), Mixin.swapcase()]
for function in ops:
    content = function(content)
print(content)

我想知道如何将其简化为

for function in Mixin:
    content = function(content)
print(content)

我尝试了 dir(Mixin) 但并不令人满意。

In [33]: [method for method in dir(Mixin) if not method.startswith("__")]
Out[33]: ['strip', 'swapcase', 'title']`

标签: python

解决方案


我同意 abarnert 的观点,这对于类 / Mixin 来说似乎是一个奇怪的用途。但是,您可以使用getattr.

getattr允许您获取给定名称的对象的属性。

因此,例如:

for method in (attr for attr in dir(Mixin) if not attr.startswith('__')):
    content = getattr(Mixin, method)()(content)

但是,考虑到迭代没有特定顺序这一事实,那么结果可能不是确定性的。

最好的方法是使用特定的顺序,例如:

for method in ['strip', 'title', 'swapcase']:
    content = getattr(Mixin, method)()(content)

推荐阅读