在Python中从一个类调用多个函数,而不在每个tim中重复类名

2024-04-26 05:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我觉得这是一个很简单的问题,但我找不到合适的答案。基本上,我有一个名为simulation的类的函数调用列表:

simulation.addGroup("teapotarmy")
simulation.populateGroup(20)
simulation.addNode("input",INPUT)
simulation.addNode("output",OUTPUT);
simulation.connectNodes("input","output");
simulation.manipOutputNode("output", "group.xvel");
simulation.manipInputNode("input", 1, 0.05);

有没有办法调用这些函数而不必每次都重复类名?大致如下:

(thethingIwant) simulation:
    addGroup("teapotarmy")
    populateGroup(20)
    addNode("input",INPUT)
    ...

我在其他编程语言中也做过,但还没有弄清楚Python中的语法。我有点模糊的记忆,它和“with”语句有关。。。? 提前谢谢。

利昂


Tags: 答案列表inputoutputgroupsimulation函数调用populategroup
3条回答

简单地说,没有。没有(好的,请看我最后的评论)方法可以做到这一点。最好的方法是将其分配给另一个较短的名称:

s = simulation
s.addGroup("teapotarmy")
...

这还不算太糟,尽管我认为普通方法更具可读性。

另外,严格来说,你不能这样做是不正确的。您可以通过编程将所有的模拟方法分配给本地名称空间,但是,这样做会很混乱,我建议您不要这样做。

示例:

from contextlib import contextmanager
import inspect

class some_class:
    def test(self):
        print("test!")

@contextmanager
def map_to_local(inst, locals):
    methods = inspect.getmembers(inst, inspect.ismethod)
    for name, method in methods:
        locals[name] = method
    yield
    for name, method in methods:
        del locals[name]

inst = some_class()
with map_to_local(inst, locals()):
    test()

注意,这是相当脆弱的-你必须小心,做一些事情,如检查你没有覆盖值,检查值没有被删除之前,上下文管理器退出,等等。。。也不清楚发生了什么。

是的,有可能,不,你不应该这样做。你现在的密码很清楚。

要使用当前设计的现有类,通常的解决方案是使用较短的变量名:

s = simulation
s.addGroup("teapotarmy")
s.populateGroup(20)
s.addNode("input",INPUT)
s.addNode("output",OUTPUT)
s.connectNodes("input","output")
s.manipOutputNode("output", "group.xvel")
s.manipInputNode("input", 1, 0.05)

也就是说,另一种解决方案是稍微改变类,让这些方法返回self。然后你可以写:

(simulation
    .addGroup("teapotarmy")
    .populateGroup(20) 
    .addNode("input",INPUT)
    .addNode("output",OUTPUT)
    .connectNodes("input","output")
    .manipOutputNode("output", "group.xvel")
    .manipInputNode("input", 1, 0.05))

通常的Python风格是让变异方法returnNone(提供变异发生的提示);但是,对于像您这样的api,返回self是一种规范,在这种api中,应用一系列转换和状态更新是很常见的。

我能想到的最贴切的事情就是利用Python函数也是类的属性(callableattributes)这一事实,因此您可以按名称“获取”它们并调用它们。。。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class Simulation(object):
  def addGroup(self, groupToAdd):
    print "Group to add: %s" % groupToAdd

  def addNode(self, inputType, inputChannel):
    print "My inputs: %s, channel: %s" % (inputType, inputChannel)

if __name__ == "__main__":
  simulation = Simulation()
  functionsToCall = [
      ("addGroup", "teapotarmy"),
      ("addNode", "input", "INPUT"),
    ]
  for functionToCall in functionsToCall:
    getattr(simulation, functionToCall[0])(* functionToCall[1:])

但这可能会使您的代码比以前更加混乱。如果其他人必须修改你的代码,这可能会使他的任务复杂化。。。相当多。:)

更多信息:Callablespacking parameters

相关问题 更多 >

    热门问题