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

相关推荐
向阳开的夏天35 分钟前
麒麟V10源码编译QT5.6.3 (x86 & arm64)
开发语言·qt
Evand J1 小时前
【MATLAB例程】TOA和TDOA混合定位,适用于二维平面的高精度定位。锚点数量、位置、测量噪声可自行调节
开发语言·matlab·定位·tdoa
念越1 小时前
数据结构:栈堆
java·开发语言·数据结构
淮北4942 小时前
pip虚拟环境包的问题
开发语言·python·pip
dear_bi_MyOnly2 小时前
【多线程——线程状态与安全】
java·开发语言·数据结构·后端·中间件·java-ee·intellij-idea
常年游走在bug的边缘2 小时前
掌握JavaScript作用域:从函数作用域到块级作用域的演进与实践
开发语言·前端·javascript
jiaguangqingpanda2 小时前
Day36-20260204
java·开发语言
ctyshr2 小时前
C++编译期数学计算
开发语言·c++·算法
打码的猿2 小时前
Qt对话框不锁死主程序的方法
开发语言·qt
努力写代码的熊大2 小时前
c++异常和智能指针
java·开发语言·c++