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.
<< 返回目录

相关推荐
JD技术委员会4 分钟前
Rust 语法噪音这么多,是否适合复杂项目?
开发语言·人工智能·rust
Hello.Reader7 分钟前
Rust 中的 `Drop` 特性:自动化资源清理的魔法
开发语言·rust·自动化
Vitalia11 分钟前
从零开始学 Rust:基本概念——变量、数据类型、函数、控制流
开发语言·后端·rust
cheungxiongwei.com11 分钟前
Rust 驱动的 Python 工具革命:Ruff 和 uv 与传统工具的对比分
python·rust·uv
小禾苗_1 小时前
C++ ——继承
开发语言·c++
李长渊哦1 小时前
Java 虚拟机(JVM)方法区详解
java·开发语言·jvm
进击ing小白1 小时前
Qt程序退出相关资源释放问题
开发语言·qt
烂蜻蜓2 小时前
前端已死?什么是前端
开发语言·前端·javascript·vue.js·uni-app
老猿讲编程2 小时前
安全C语言编码规范概述
c语言·开发语言·安全
web135085886353 小时前
Python大数据可视化:基于python的电影天堂数据可视化_django+hive
python·信息可视化·django