首页 > python这个例子中,__sub__()内置函数到底什么作用?

python这个例子中,__sub__()内置函数到底什么作用?

class superList(list):
    def __sub__(self,b):
        a = self[ :]
        b = b[ : ]
        while len(b) > 0:
            element_b = b.pop()
            if element_b in a:
                a.remove(element_b)
        return a

print superList([1,2,3])-superList([3,4])

不是很明白这里的__sub__()作用,以及下面的a = self[:],b=b[:]
新手,看的一个博客教程,遇到这个问题~


A-B 么。

class superList(list):
    def __sub__(self,b):
        a = self[:] # 这是一个 copy,赋值给一个临时变量
        b = b[:] # 同上
        while len(b) > 0: # 循环,当 b 列表中仍有元素时
            element_b = b.pop() # 移除 b 中一个元素,并将此元素赋值给 变量 element_b
            if element_b in a: # 如果 element_b 在 列表 a 也就是 self 中
                a.remove(element_b) # 减法开始了,从 a 也就是 self 也就是 A-B 的 A 中,移除 B 元素
        return a # 返回列表 a
print superList([1,2,3])-superList([3,4])

这是一个对 list 类的运算符重载的示例。如果直接用 lista - listb,会报错,因为 python 的 list 不支持这种运算。

题主可以尝试重载一下 __add__ 试试,正常的 add,就是加嘛,但我们这里让它变成

#!/usr/bin/env python3
# coding=utf-8

class superList(list):
    def __sub__(self, b):
        a = self[:]
        b = b[:]
        while len(b) > 0:
            element_b = b.pop()
            if element_b in a:
                a.remove(element_b)
        return a

    def __add__(self, other):
        a = self[:]
        b = other[:]
        while len(b) > 0:
            element_b = b.pop()
            if element_b in a:
                a.remove(element_b)
        return a


lista = [1, 2, 3, 9]
listb = [3, 4, 10]

print(superList(lista) + superList(listb))
print(lista + listb)

print(superList(lista) - superList(listb))
print(lista - listb) # 报错
【热门文章】
【热门文章】