python这个例子中,__sub__()内置函数到底什么作用?
大家讲道理
大家讲道理 2017-04-17 16:23:23
[Python讨论组]
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[:]
新手,看的一个博客教程,遇到这个问题~

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(1)
PHP中文网

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) # 报错
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号