【发布时间】: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
我已将变量 f 分配给方法 list.append。如何使用 f 调用该方法?我尝试了以下方法,但它会产生错误。
f = list.append
a = []
a.f([1])
AttributeError: 'list' object has no attribute 'f'
【问题讨论】:
标签: python list methods append attributeerror
你传递给它一个列表来操作:
f(a, 1)
但是……你为什么需要这个?这很不寻常...
作为替代方案:
a = []
f = a.append
f(1)
f 现在是绑定方法(列出a)。
【讨论】:
def method(self, argument)。 self 是对当前对象的显式引用,因此当您编写 a = []; a.append(1) 时,这实际上与 a = []; list.append(a, 1) 相同。我知道这一点是因为我在 iPython 中进行了实验并阅读了文档,而且观看 PyCon 演示文稿也非常有用。