我正在尝试调用一个对象函数,该函数还允许通过同一对象调用多个不同的函数:
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/