You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中list的特殊方法(__xx__)使用方式及示例讲解请求

关于Python列表方法的使用说明

首先先把你贴的dir(list)结果用代码块整理清晰:

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

核心结论:完全不需要自己编写类

这些方法都是Python内置list类型自带的方法,你只要创建一个列表实例,就能直接调用它们,根本不用自己定义类。下面分两类给你举简单易懂的例子:


一、普通方法(不带双下划线的)

这些是日常开发中用得最多的列表操作,直接用列表实例.方法名()调用就行:

  • append():给列表末尾添加单个元素
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)  # 输出: ['apple', 'banana', 'orange']
  • pop():删除并返回列表指定位置的元素(默认删最后一个)
last_fruit = fruits.pop()
print(last_fruit)  # 输出: orange
print(fruits)      # 输出: ['apple', 'banana']

# 指定索引删除第二个元素
fruits.pop(1)
print(fruits)      # 输出: ['apple']
  • sort():对列表原地排序(会修改原列表)
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)  # 输出: [1, 2, 3, 4]
  • count():统计某个元素在列表中的出现次数
nums = [1, 2, 2, 3, 2]
print(nums.count(2))  # 输出: 3

二、魔法方法(带双下划线的)

这些方法大多是Python内部用来实现语法功能的“底层方法”,你很少需要直接调用它们的名字,而是通过对应的语法触发:

  • add():对应+运算符,用来拼接两个列表
list1 = [1, 2]
list2 = [3, 4]
# 等价于手动调用 list1.__add__(list2)
combined = list1 + list2
print(combined)  # 输出: [1, 2, 3, 4]
  • len():对应len()函数,获取列表长度
my_list = [10, 20, 30]
# 等价于 my_list.__len__()
length = len(my_list)
print(length)  # 输出: 3
  • getitem():对应索引访问list[index]
first_element = my_list[0]
# 等价于 my_list.__getitem__(0)
print(first_element)  # 输出: 10
  • contains():对应in关键字,判断元素是否在列表中
# 等价于 my_list.__contains__(20)
is_present = 20 in my_list
print(is_present)  # 输出: True

简单总结:普通方法直接用列表点调用就行,魔法方法靠Python的语法糖触发,日常开发基本不用手动写__xxx__()的形式去调用~

内容的提问来源于stack exchange,提问作者Mohan. A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:17:50