【问题标题】:What is the difference between the apply() function and a function call using the object of the class?apply() 函数和使用类对象的函数调用有什么区别?
【发布时间】:2017-03-31 09:29:42
【问题描述】:

将 Atom 视为一个类

  • form.name 是一个字符串
  • convert 返回值列表

以下两行有什么区别?

  • apply(Atom, [form.name] + list([convert(arg, subst) for arg in list(form.args)]))

  • Atom(form.name, [convert(arg, subst) for arg in form.args])

来自文档,

申请(...) 应用(对象 [,args [,kwargs]])-> 值
使用从元组 args 中获取的位置参数调用可调用对象, 和取自可选字典 kwargs 的关键字参数。 请注意,类是可调用的,具有 call() 方法的实例也是如此。

我无法理解这两行之间的区别。我正在尝试在 Python 3.5 中找到 apply(Atom, [form.name] + list([convert(arg, subst) for arg in list(form.args)])) 的等效代码

【问题讨论】:

    标签: python python-2.7 python-3.x apply


    【解决方案1】:

    applyunpacking arguments 的老派1 方式。换句话说,以下都产生相同的结果:

    results = apply(foo, [1, 2, 3])
    results = foo(*[1, 2, 3])
    results = foo(1, 2, 3)
    

    由于您在 apply 不再存在的 python3.5 中工作,因此该选项无效。此外,您将参数作为列表使用,因此您也不能真正使用第三个选项。剩下的唯一选择是第二个。我们可以很容易地将您的表达式转换为该格式。 python3.5 中的等价物是:

    Atom(*([form.name] + [convert(arg, subst) for arg in list(form.args)]))
    

    1在 python2.3 中已弃用!

    【讨论】:

    • 它有效.. 但你能告诉我这里使用了哪个概念,以便我可以阅读它。什么是原子(*...)? * 代表什么?
    • @Dennis -- 这就是我们现在在现代 python 中解包参数的方式。我在上面添加了一个链接,您可以在 python 教程中阅读更多相关信息
    • @Dennis -- 另外,请注意您发布的链接。具体来说,该链接指定了在函数定义点具有* 的含义。这个问题更多地是关于在函数 call 点有一个* 意味着什么。它们是密切相关的概念(密切相关,以至于当您使用它一段时间后很容易忽略它们不同的事实),但它们是可以分开理解的不同事物。
    猜你喜欢
    • 2010-10-28
    • 2021-04-13
    • 1970-01-01
    • 2014-03-16
    • 2013-03-30
    相关资源
    最近更新 更多