在单条数据上运行一堆 python 方法
我想在给定一些数据的情况下运行一组方法。我想知道如何删除或选择运行不同的方法来运行。我想将它们分组到一个更大的方法中,以便我可以调用它;它将沿着测试用例的路线进行。
在代码中:现在这些是处理数据的方法。有时我可能想运行所有三个或其子集来收集有关此数据集的信息。
def one(self):
pass
def two(self):
pass
def three(self):
pass
我希望能够通过另一个调用来调用这些方法,这样我就不必输入 run this;运行这个。我正在寻找一种优雅的方式来通过一次调用运行一堆方法,这样我就可以选择运行哪些方法。
期望的结果
def run_methods(self, variables):
#runs all three or subset of
我希望我的问题很清楚。我只是在寻找一种优雅的方式来做到这一点。就像 Java 中的反射一样。
请并谢谢。
I would like to run a set of methods given some data. I was wondering how I can remove or chose to run different methods to be run. I would like to groups them within a larger method so I can call it; and it will go along the lines of test case.
In code: Now these are the methods that process the data. I may sometimes want to run all three or a subset thereof to collect information on this data set.
def one(self):
pass
def two(self):
pass
def three(self):
pass
I would like to be able to call of these methods with another call so I dont have to type out run this; run this. I am looking for elegant way to run a bunch of methods through one call so I can pick and choose which gets run.
Desired result
def run_methods(self, variables):
#runs all three or subset of
I hope I have been clear in my question. I am just looking for an elegant way to do this. Like in Java with reflection.
Please and thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
发送你想要作为参数运行的方法:
然后调用类似的东西:
这是Python中将函数作为第一类对象的好处
对于注释中OP的问题(函数的不同参数),一个脏的解决方案(对此感到抱歉):
将函数视为字典的键,这
您可以使用其他容器将方法及其变量一起发送,但是如果您的方法/函数使用不同数量的参数,则您不能使用它,
因为它期望 是很好的选择所有方法的参数数量相同。在这种情况下,您可以使用 *args:
Send the methods you want to run as a parameter:
then call something like:
This is the nice thing of having functions as first-class objects in Python
For the question of the OP in the comment (different parameters for the functions), a dirty solution (sorry for that):
You could use other containers to send methods together with their variables but it is nice to see a function as the key of a dictionary
if your methods/functions use different numbers of parameters you can not use
because it expects the same number of parameters for all methods. In this case you can use *args:
如果您通常执行所有功能但有时会出现异常,那么默认情况下完成它们会很有用,但可以选择禁用它们,如下所示:
If you normally do all the functions but sometimes have exceptions, then it would be useful to have them done by default, but optionally disable them like this:
回答评论中有关传递任意值的问题:
但在这一点上,它看起来比它的价值更多的代码!
To answer the question in the comment regarding passing arbitrary values:
But at this point, it's looking like more code than it's worth!