文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

python接口,继承,重载运算符详解

2024-04-02 19:55

关注

1. 序列__getitem__

如果没有 __iter__ 和 __contains__ 方法,
Python 会调用 __getitem__ 方法,
设法让 迭代 和 in 运算符可用


class Foo:
    def __getitem__(self, pos):
        return range(0, 30, 10)[pos]

f = Foo()
print(f[1])  # 10
for i in f:
    print(i)  # 0, 10, 20
# 如果没有 __iter__ 和 __contains__ 方法,
# Python 会调用 __getitem__ 方法,
# 设法让迭代和 in 运算符可用

2. __setitem__


import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])

class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA')
    suits = 'spades diamonds clubs hearts'.split()
    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]
    def __len__(self):
        return len(self._cards)
    def __getitem__(self, position):
        return self._cards[position]
	def __str__(self):
        return ",".join(str(i) for i in self._cards)
from random import shuffle
deck = FrenchDeck()
print(str(deck))
# Card(rank='2', suit='spades'),Card(rank='3', suit='spades'),Card(rank='4', suit='spades'),Card(rank='5', suit='spades'),Card(rank='6', suit='spades'),Card(rank='7', suit='spades'),Card(rank='8', suit='spades'),Card(rank='9', suit='spades'),Card(rank='10', suit='spades'),Card(rank='J', suit='spades'),Card(rank='Q', suit='spades'),Card(rank='K', suit='spades'),Card(rank='A', suit='spades'),Card(rank='2', suit='diamonds'),Card(rank='3', suit='diamonds'),Card(rank='4', suit='diamonds'),Card(rank='5', suit='diamonds'),Card(rank='6', suit='diamonds'),Card(rank='7', suit='diamonds'),Card(rank='8', suit='diamonds'),Card(rank='9', suit='diamonds'),Card(rank='10', suit='diamonds'),Card(rank='J', suit='diamonds'),Card(rank='Q', suit='diamonds'),Card(rank='K', suit='diamonds'),Card(rank='A', suit='diamonds'),Card(rank='2', suit='clubs'),Card(rank='3', suit='clubs'),Card(rank='4', suit='clubs'),Card(rank='5', suit='clubs'),Card(rank='6', suit='clubs'),Card(rank='7', suit='clubs'),Card(rank='8', suit='clubs'),Card(rank='9', suit='clubs'),Card(rank='10', suit='clubs'),Card(rank='J', suit='clubs'),Card(rank='Q', suit='clubs'),Card(rank='K', suit='clubs'),Card(rank='A', suit='clubs'),Card(rank='2', suit='hearts'),Card(rank='3', suit='hearts'),Card(rank='4', suit='hearts'),Card(rank='5', suit='hearts'),Card(rank='6', suit='hearts'),Card(rank='7', suit='hearts'),Card(rank='8', suit='hearts'),Card(rank='9', suit='hearts'),Card(rank='10', suit='hearts'),Card(rank='J', suit='hearts'),Card(rank='Q', suit='hearts'),Card(rank='K', suit='hearts'),Card(rank='A', suit='hearts')
shuffle(deck)  # TypeError: 'FrenchDeck' object does not support item assignment

加入__setitem__


    def __setitem__(self, key, value):
        self._cards[key] = value

shuffle(deck) 
print(str(deck))
# 牌被随机打乱了
# Card(rank='6', suit='hearts'),Card(rank='2', suit='spades'),Card(rank='3', suit='hearts'),Card(rank='A', suit='clubs'),Card(rank='7', suit='clubs'),Card(rank='Q', suit='diamonds'),Card(rank='5', suit='hearts'),Card(rank='6', suit='spades'),Card(rank='5', suit='diamonds'),Card(rank='8', suit='diamonds'),Card(rank='K', suit='hearts'),Card(rank='Q', suit='hearts'),Card(rank='8', suit='hearts'),Card(rank='3', suit='diamonds'),Card(rank='Q', suit='clubs'),Card(rank='A', suit='diamonds'),Card(rank='9', suit='hearts'),Card(rank='7', suit='diamonds'),Card(rank='A', suit='spades'),Card(rank='J', suit='hearts'),Card(rank='3', suit='clubs'),Card(rank='4', suit='hearts'),Card(rank='Q', suit='spades'),Card(rank='10', suit='diamonds'),Card(rank='10', suit='hearts'),Card(rank='K', suit='diamonds'),Card(rank='2', suit='diamonds'),Card(rank='4', suit='spades'),Card(rank='3', suit='spades'),Card(rank='7', suit='hearts'),Card(rank='9', suit='clubs'),Card(rank='J', suit='clubs'),Card(rank='J', suit='diamonds'),Card(rank='10', suit='spades'),Card(rank='4', suit='diamonds'),Card(rank='7', suit='spades'),Card(rank='9', suit='diamonds'),Card(rank='2', suit='hearts'),Card(rank='6', suit='clubs'),Card(rank='K', suit='clubs'),Card(rank='4', suit='clubs'),Card(rank='A', suit='hearts'),Card(rank='K', suit='spades'),Card(rank='2', suit='clubs'),Card(rank='J', suit='spades'),Card(rank='8', suit='spades'),Card(rank='5', suit='spades'),Card(rank='9', suit='spades'),Card(rank='10', suit='clubs'),Card(rank='8', suit='clubs'),Card(rank='6', suit='diamonds'),Card(rank='5', suit='clubs')

或者 在类外打补丁 FrenchDeck.__setitem__ = 函数


def set_card(deck, position, card):
    deck._cards[position] = card

FrenchDeck.__setitem__ = set_card

3. 抽象基类


class Test:
    def __len__(self):
        return 24

from collections import abc
print(isinstance(Test(), abc.Sized)) # True

只要实现了 __len__() 方法,就可以被 abc.Sized 识别为子类

4. 不要直接子类化内置类型


class AnswerDict(dict):
    def __getitem__(self, key):
        return 24

ad = AnswerDict(a="good")
print(ad['a'])  # 24
d = {}
d.update(ad)
print(d['a'])  # good
print(ad)  # {'a': 'good'}
print(d)  # {'a': 'good'}

直接子类化内置类型(如 dict、list 或 str)容易出错, 因为 内置类型的方法 通常会 忽略用户覆盖的方法。

不要子类化内置 类型,用户自己定义的类 应该继承 collections 模块 中的类,例如 UserDict、UserList 和 UserString,这些类做了特殊设计,因 此易于扩展

5. 继承顺序


import collections

class AnswerDict2(collections.UserDict):
    def __getitem__(self, key):
        return 24
ad = AnswerDict2(a="good")
print(ad['a'])  # 24
d = {}
d.update(ad)
print(d['a'])  # 24
print(ad)  # {'a': 'good'}
print(d)  # {'a': 24}

6. 重载运算符


在这里插入图片描述

不可变类型,,一定不能实现就地特殊方法

__iadd__等增量赋值特殊方法 必须返回 self

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注编程网的更多内容!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯