常见的内置方法:__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))
相关推荐
zone773918 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant18 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来19 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_19 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend20 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽20 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_2 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮2 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling2 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python