python - 在 python 中使用 getattr 的替代方法?

标签 python python-2.7 sunburnt

我正在尝试调用一个对象函数,该函数还允许通过同一对象调用多个不同的函数:

for eg: sort(), facet(),exclude() are different functions with their arguments and sort_flag, facet_flag and exclude_flag as condition set to true or false

可以称为:

si = sunburnt.SolrInterface("url","schema.xml")
response = si.query(arg1).facet(arg2).sort(arg3).exclude(arg4)

在某些情况下,我不需要同时调用所有这些函数,或者可能我没有调用这些函数的所有参数,反之亦然。在这种情况下,我怎样才能调用 si.facet(args).sort(args) 这样的东西:

if sort_flag:
  --append sort function to the query
if exclude_flag:
  -- append exclude function

可以使用 getattr 来实现这一点,但使用函数参数使用它会令人困惑,同时它可能会生成大量 if 检查语句(对于接近 3 个阶乘语句的 3 个标志)

最佳答案

我不确定我是否理解你的意思,但是你不能这样做吗?

si = sunburnt.SolrInterface("url","schema.xml")
query = si.query(arg1).facet(arg2)

if sort_flag:
  query = query.sort(arg3)
if exclude_flag:
  query = query.exclude(arg4)

response = query.execute()

关于python - 在 python 中使用 getattr 的替代方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15086592/

相关文章:

Python-for语句理解

python - Raspberry pi 3.0 i2c SMBus 问题

python - 导入 basemap 时出现ImportError

python - sunburnt - 如何查看生成的查询 URL

python - 在数据框列上应用 curve_fit

python - 如何检查字典是否只有一个值为 "1"的键

python - 如何在 Python 中获取组合 Unicode 字符串的 "visible"长度?

python - Sunburnt solr 通配符 * :*

使用它的两个实例时出现 Python_textinput 问题