Python自学 - 类进阶(可调用对象)

<< 返回目录

1 Python自学 - 类进阶(可调用对象)

  可调用对象Python中有很重要的作用,那什么是可调用对象呢?

可以简单的理解为,凡是对象可以加括号给参数的都叫可调用对象,如:obj(x)obj就是可调用对象,因此,不难理解,最基础的可调用对象就是函数

  我们自定义的类,能不能做为可调用对象呢? 答案是肯定的!

可能很多读者存在疑问,前文说可调用对象很重要,那具体有什么用呢?

1.1 可调用对象的用途

1.1.1 函数式编程

函数式编程章节中,我们介绍了lambdamapfilter函数,他们的参数需要输入一个函数,迭代器中的成员逐个让这个函数来处理,这里的函数就是一个可调用对象。

示例1:使用函数式编程将列表成员平方

py 复制代码
def square(x):
    return x ** 2
    
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(square, numbers))
print(squared_numbers)  # 输出: [1, 4, 9, 16, 25]

示例2:由可调用的类对象来替换函数式编程中的函数

py 复制代码
class Square:
    def __init__(self):
        print("初始化")
    def __call__(self, x):
        return x * x

s = Square() #输出:初始化

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(s, numbers))
print(squared_numbers)  # 输出: [1, 4, 9, 16, 25]

示例中创建了一个Square类的对象s,然后将对象s替换示例1中的函数square传递给map()做参数。

1.1.2 回调函数

  在GUI编程中,界面元素的事件处理,往往都由需要一个函数来处理,这个函数一般就是回调函数。

示例3:回调函数处理按钮点击事件

py 复制代码
import tkinter as tk

def on_button_click():
    print("Button clicked")

root = tk.Tk()
button = tk.Button(root, text="Click me", command=on_button_click)
button.pack()
root.mainloop()

示例中的command=on_button_click就是回调函数赋值,注意on_button_click是一个函数。

1.1.3 实现协议和接口

  实现 __iter____next__ 方法的对象是可调用对象,可以使用 for 循环迭代。

py 复制代码
class MyIterator:
    def __init__(self, limit):
        self.limit = limit
        self.counter = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.counter < self.limit:
            value = self.counter
            self.counter += 1
            return value
        else:
            raise StopIteration

for i in MyIterator(5):
    print(i)  # 输出: 0 1 2 3 4

1.1.4 类和对象的行为定制

实现 __call__ 方法的对象可以像函数一样调用,用于定制对象的行为,实现__call__方法在前面函数式编程已经做了举例。

1.1.5 可调用对象做修饰器改变其他函数行为

py 复制代码
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
#输出:
#Something is happening before the function is called.
#ello!
#Something is happening after the function is called.

被装饰过的函数say_hello()行为已经发生了变化。

1.1.6 可调用对象做对象工厂

py 复制代码
def create_shape(shape_type):
    if shape_type == 'circle':
        class Circle:
            def __str__(self):
                return "Circle"
        return Circle()
    elif shape_type == 'square':
        class Square:
            def __str__(self):
                return "Square"
        return Square()

circle = create_shape('circle')
square = create_shape('square')
print(circle)  # 输出: Circle
print(square)  # 输出:Square

1.1.7 可调用对象做调度表,减少大量if-else

py 复制代码
def action_a():
    print("Action A")

def action_b():
    print("Action B")

dispatch_table = {'a': action_a, 'b': action_b}

def perform_action(action):
    if action in dispatch_table:
        dispatch_table[action]()

perform_action('a')  # 输出: Action A

示例中只有两个分支,如果有多个分支,效果将会更好!


作者声明:本文用于记录和分享作者的学习心得,可能有部分文字或示例来源自豆包AI,由于本人水平有限,难免存在表达错误,欢迎留言交流和指教!

Copyright © 2022~2025 All rights reserved.
<< 返回目录

相关推荐
曲幽12 分钟前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817532 小时前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱16 小时前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei19 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi001 天前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn1 天前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵2 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup112 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill