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

相关推荐
veminhe9 小时前
python(五)rag学习一:02向量
python
身如柳絮随风扬9 小时前
Java对象在计算机中的执行原理:从JVM内存模型到对象创建全过程
java·开发语言·jvm
河西石头9 小时前
听AI的血的教训!PPOCRLabel部署与PyQt5的安装避坑-百分百成功!
开发语言·人工智能·python·pyqt5安装·ppocrlabel的部署
BU摆烂会噶9 小时前
【LangGraph】 流式处理入门
人工智能·python·langchain·人机交互
野生技术架构师9 小时前
我总结了这份2026最新版Java面试题库(背完这一套就够了)
java·开发语言·面试
AIGC设计所9 小时前
网络安全8大就业领域和待遇对比!
运维·开发语言·网络·安全·web安全·php
xxjj998a9 小时前
PHP与汇编:从Web到硬件的编程差异
开发语言·汇编·php
计算机毕业编程指导师9 小时前
【Python大数据项目推荐】基于Hadoop+Django脑卒中风险分析系统源码解析 毕业设计 选题推荐 毕设选题 数据分析 机器学习 数据挖掘
大数据·hadoop·python·计算机·spark·毕业设计·脑卒中
bestcxx9 小时前
多个维度对 Java、Python、C#、Go 这四种主流编程语言进行比较
java·python·c#
装杯让你飞起来啊9 小时前
Kotlin 条件判断 if / when 与智能转换 smart cast
开发语言·python·kotlin