当我使用list.extend调用它时,为什么extend方法不起作用?

问题描述 投票:-4回答:1

当我使用list.extend(list_object)在python中调用list的extend方法时,我收到一个错误。为什么会这样?我没有声明列表类的对象,而是使用list.extend直接调用extend。以下是我写的代码。

l=list()
l2=[1,2,3,4]
print(list.extend(l2))# throws an error.I was under the impression that this is same as the below statement
print(l.extend(l2)) #doesnt throw an error

也,

class student():
        a=1

s=student()
s.a #prints 1.
student.a #also prints 1. Here the previous error isnt coming.

为什么会这样?

python
1个回答
2
投票

两种情况都不一样。

在第一种情况下,您通过类调用内置类的方法(可调用属性),然后调用类的实例。在第二种情况下,您将通过实例访问类的非可调用属性,然后通过类访问。方法是可调用的,为了调用它们,您需要尊重方法的签名,这与第二种情况不同。

要通过列表类本身使用extend,您需要将列表实例作为第一个参数传递,因为Python中的vanilla方法通常需要一个实例作为第一个参数:

list.extend(l, l2) # extends l with l2

请注意,当您通过l.extend(l2)中的实例调用extend时,将隐式传递该实例。

© www.soinside.com 2019 - 2024. All rights reserved.