简体   繁体   English

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

[英]Why is extend method not working when i call it using list.extend?

When i call the extend method of list in python using list.extend(list_object) i get an error.当我使用 list.extend(list_object) 在 python 中调用列表的扩展方法时,出现错误。 Why is this happening?为什么会这样? Instead of declaring an object of list class i am directly calling the extend using list.extend.我没有声明列表类的对象,而是使用 list.extend 直接调用扩展。 the following is the code which i wrote.以下是我写的代码。

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

Also,还,

class student():
        a=1

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

Why is this so?为什么会这样?

Both cases are not the same.这两种情况并不相同。

In the first case, you're calling a method (a callable attribute) of a builtin class via the class and then an instance of the class.在第一种情况下,您通过类调用内置类的方法(可调用属性),然后是类的实例。 In the second case, you're accessing a non callable attribute of the class, via the instance and then via the class.在第二种情况下,您通过实例然后通过类访问类的不可调用属性。 Methods are callable and in order to call them, you need to respect the signature of the method, unlike the second case.方法是可调用的,为了调用它们,您需要尊重方法的签名,与第二种情况不同。

To use extend via the list class itself, you need to pass a list instance as first argument, as vanilla methods in Python usually require an instance as first argument:要通过列表类本身使用extend ,您需要传递一个列表实例作为第一个参数,因为 Python 中的 vanilla 方法通常需要一个实例作为第一个参数:

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

Note that the instance is implicitly passed when you call extend via the instance in l.extend(l2) .请注意,当您通过l.extend(l2)的实例调用扩展时,该实例是隐式传递的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM