常见的内置方法:__call__,__getitem__,__iter__,__next__

1.__call__方法

在创建好一个实例后,直接调用一个实例会报错。但使用__call__后,可以让这个实例可以像方法一样被调用(就是一个函数后面加个括号的函数调用形式)

python 复制代码
class Person:
    pass

p1 = Person()
p1()     # 实例这样无法直接被调用


 使用类和__call__方法
class PenFactory(object):
    def __init__(self, p_type):
        self.p_type = p_type
    def __call__(self, p_color):
        print(f"创建了一个{self.p_type}类型的钢笔,它的颜色是{p_color}")

gangbiF = PenFactory("钢笔")        #实例化
gangbiF("黄色")                     
#直接调用实例,实例可以像方法一样被调用调用的是类中的__call__方法

2.索引操作(使对象具有像字典一样的索引操作)

python 复制代码
class Person:
    def __init__(self):
        self.cache = {}

    def __setitem__(self, key, value):
        # print("setitem", key, value)
        self.cache[key] = value

    def __getitem__(self, item):
        # print("getitem", item)
        return self.cache[item]

    def __delitem__(self, key):
        # print("delitem", key)
        del self.cache[key]

p = Person()
p["name"] = "sz"

print(p["name"])

del p["name"]

# print(p["name"])
print(p.cache)

3.遍历操作(使得实例化的对象可以被遍历)

注:一般实现遍历,会用到两种方法:

  1. for...in...

  2. 使用next迭代 (针对迭代器)

3.1方法一:类中使用__getitem__方法

python 复制代码
class Person:
    def __init__(self):
        self.result = 1

    def __getitem__(self, item):
        self.result += 1
        if self.result >= 6:
            raise StopIteration("停止遍历")

        return self.result

p = Person()

for i in p:
    print(i)

3.2方法二:使用__iter__和__next__方法

python 复制代码
class Person:
    def __init__(self):
        self.result = 1

    def __iter__(self):
        print("iter")
        return self

    def __next__(self):
        self.result += 1
        if self.result >= 6:
            raise StopIteration("停止遍历")
        return self.result

p = Person()

for i in p:
    print(i)

# print(next(p))
# print(next(p))
# print(next(p))
# print(next(p))
# print(next(p))
# print(next(p))
相关推荐
羲云网络5 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
曲径海盗6 小时前
【Python 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn6 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
VW_4049 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
yiangL_10 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶10 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
geovindu12 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk816313 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
敲上瘾13 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
卷无止境14 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python