什么是抽象函数而不是对象的优雅方法?
我有一个通过 telnet/pexpect 登录传感器并充当数据收集器的功能。
我不想重写登录、获取数据并从中解析出相关输出的部分(pexpect)。但是,我需要使用此代码及其收集的数据执行不同的操作,
例如,我可能需要:
返回第一个读数之前的时间
获取不同数量的传感器读数的平均值
返回状态(这是一份数据)或返回传感器 阅读(这是一个单独的部分 data)从输出
最终,它仍然应该登录并解析相同的输出,我想为该部分使用一个代码块。
在代码的更高层,它会被立即使用。当我调用它时,我知道我需要收集什么类型的数据,仅此而已。构造对象太笨拙了。
我的用法已经超出了向单个函数添加更多参数的范围。
有什么想法吗?
I have a function that logs into a sensor via telnet/pexpect and acts as a data collector.
I don't want to rewrite the part that logs in, grabs the data, and parses out relevant output from it (pexpect). However, I need to do different things with this code and the data it gathers
For example, I may need to:
Time until the first reading is returned
Take the average of a varying number of sensor readings
Return the status (which is one piece of data) or return the sensor
reading (which is a separate piece of
data) from the output
Ultimately, it should still login and parse output the same and I want to use one code block for that part.
Higher up in the code, it's being used instantaneously. When I call it, I know what type of data I need to gather and that's that. Constructing objects is too clumsy.
My usage has outstripped adding more arguments to a single function.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是很常见的情况,我很惊讶你还没有做其他人所做的事情。
重构您的函数,将其分解为更小的函数。
函数是对象,可以作为参数传递给其他函数。
现在你可以这样做了。
这只是使用函数对象进行面向对象编程。
This is such a common situation, I'm surprised you haven't already done what everyone else does.
Refactor your function to decompose it into smaller functions.
Functions are objects, and can be passed as arguments to other functions.
Now you can do this.
It's just OO programming with function objects.
您能否将数据处理函数传递给您作为参数描述的函数?
这可能或多或少优雅,具体取决于您的品味。
(请原谅我:我对 pexpect 一无所知,我什至可能误解了你的问题!)
Could you pass a data processing function to the function you described as an argument?
That may be more or less elegant, depending on your taste.
(Forgive me: I know nothing about pexpect, and I may even have misunderstood your question!)