【问题标题】:Use argument to call specific method [duplicate]使用参数调用特定方法[重复]
【发布时间】:2015-11-04 19:58:56
【问题描述】:

假设我有一个类Bucket 和一个函数do_thing(这是一个非常简化的示例)。我想将一个参数传递给do_thing,它将创建一个Bucket 的实例并对该Bucket 对象执行指定的方法。

Class Bucket:
    __init__(self, volume):
        ...
    def fill(self):
        ...
    def empty(self):
        ...

def do_thing(method, vol):
    A = Bucket(vol)
    A.method()

这不起作用,显然如果我尝试do_thing("fill", 200),它会引发AttributeError: Bucket instance has no attribute 'method'。那么如何调用具体的方法(本例为fill?)

【问题讨论】:

  • getattr(A, method)()? Python 不会神奇地将属性名称method 替换为不相关参数method 的值。另见stackoverflow.com/q/3521715/3001761
  • @jonrsharpe 酷。我的谷歌搜索没有返回那个特定的问题,但希望从现在开始它会通过这个

标签: python arguments


【解决方案1】:

嗯,错误说明了一切。 Bucket 没有名为“method”的方法,实际上,您没有编写代码,只有“fill”和“empty”。

现在你说你用 do_thing(fill, 200) 调用那个函数。

“填充”参数究竟是什么?如果代码真的是这样,python 将在到达 AttributeError 之前失败,因为 'fill' 是一个未定义的变量

NameError: name 'fill' is not defined

您可以将要使用的方法的名称作为字符串传递。在这种情况下,您需要:

def do_thing(method, vol):
    A = Bucket(vol)
    getattr(A, method)()

do_thing('fill', 200)

但是,我建议您仔细考虑您想要做什么。这不是一个非常干净的代码。你应该问问自己是否真的需要走这条路。

【讨论】:

    猜你喜欢
    • 2018-12-21
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 2013-08-04
    相关资源
    最近更新 更多