python - 迭代指定类的方法
问题描述
假设这样一个最小的 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']`
解决方案
我同意 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)
推荐阅读
- multithreading - 如何使用安全异常库捕获异步异常?
- saml-2.0 - LDAP 是否支持 SAML 2.0 请求?
- r - acf() 函数“lag.max”参数说明
- mongodb - 相同的 mongodb 查询给出不同的解释计划
- sql-server - 使用 sqlcmd 时仅返回受影响的 N 行
- webpack - SyntaxError:意外的关键字“const”。严格模式不支持 const 声明
- javafx-8 - 我想在编辑表格视图单元格文本字段后,当我输入时我想自动建议单词
- apache-spark - 使用 Overwrite 模式时 Spark 不会删除 MemSql 中的旧数据
- python - 如何减少 Django 在查询子模型属性时进行的数据库调用次数?
- asp.net-mvc - 我想在 kendo ui gridview Nopcommerce 中添加 if 条件