【问题标题】:how to use methods in a module when it is assigned to a variable将模块分配给变量时如何使用模块中的方法
【发布时间】:2018-06-24 17:53:44
【问题描述】:

我已将变量 f 分配给方法 list.append。如何使用 f 调用该方法?我尝试了以下方法,但它会产生错误。

f = list.append
a = []
a.f([1])

AttributeError: 'list' object has no attribute 'f'

【问题讨论】:

    标签: python list methods append attributeerror


    【解决方案1】:

    你传递给它一个列表来操作:

    f(a, 1)
    

    但是……你为什么需要这个?这很不寻常...

    作为替代方案:

    a = []
    f = a.append
    f(1)
    

    f 现在是绑定方法(列出a)。

    【讨论】:

    • 我想从包含函数名称的给定字符串中调用一个函数。我成功地为我的用户定义了一个,但未能在模块内调用方法。谢谢它的工作原理。我是python的新手。所以我想问另一个问题。你怎么知道 f 现在有两个参数?
    • @SabbirAhmed 当你编写 python 类时,你几乎总是这样做:def method(self, argument)self 是对当前对象的显式引用,因此当您编写 a = []; a.append(1) 时,这实际上与 a = []; list.append(a, 1) 相同。我知道这一点是因为我在 iPython 中进行了实验并阅读了文档,而且观看 PyCon 演示文稿也非常有用。
    猜你喜欢
    • 2017-12-27
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2011-12-19
    • 1970-01-01
    相关资源
    最近更新 更多