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

相关推荐
星梦清河几秒前
Java—异步编程
java·开发语言
接着奏乐接着舞12 分钟前
dto 转entity方法
java·开发语言
0x000720 分钟前
译 Anders Hejlsberg 谈 C# 与 .NET
开发语言·c#·.net
TechWayfarer24 分钟前
IP精准定位服务在快递网点规划中的应用:如何用客户位置数据辅助选址
大数据·网络·python·tcp/ip·交通物流
czhaii26 分钟前
基于51单片机的Modbus从机通信系统
开发语言·单片机
elseif12328 分钟前
【C++】vector 详细版
开发语言·c++·算法
codingPower36 分钟前
JAVA后端安全进阶:基于HMAC-SHA256+Nonce+Timestamp的API防重放攻击方案
java·开发语言·spring boot·安全
暗冰ཏོ37 分钟前
Go 语言从入门到后端项目实战完整指南
开发语言·后端·golang·go·go语言
CSND74037 分钟前
零基础学Python合集---3:字符串的定义和常用方法
人工智能·python
Xin_ye1008639 分钟前
C# 零基础到精通教程 - 第十七章:前端集成——Blazor 基础
开发语言·c#