在看Flask源码时发现的偏函数,现整理一下一些可能的应用例子
示例1
from functools import partial
def lookup_req_object(name):
top = instance_stack.pop()
return getattr(top, name, None)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def newBee(self):
print("永远{}岁".format(self.age))
class Student(Person):
def __init__(self, name, age, score):
super().__init__(name, age)
self.score = score
def printScore(self):
print("{}的分数为:{}".format(self.name, self.score))
class Teacher(Person):
def __init__(self, name, age, salary):
super().__init__(name, age)
self.salary = salary
def printSalary(self):
print("{}的工资为:{}".format(self.name, self.salary))
s1 = Student("安分守己的小明", 17, 1)
t1 = Teacher("法外狂徒张三", 18, 9999)
instance_stack = [s1, t1]
lookup_req_object('newBee')()
lookup_req_object('newBee')()
"""
结果:
永远18岁
永远17岁
"""
instance_stack = [s1, t1]
a = lookup_req_object('printSalary')
b = lookup_req_object('printScore')
if a:
a()
if b:
b()
"""
结果:
法外狂徒张三的工资为:9999
安分守己的小明的分数为:1
"""
示例2
from functools import partial
int2 = partial(int, base=2) # 把 int 的转换设为二进制了,这里 base 是 int 函数表示进制的参数。
print(int2('1000000')) # 结果为:64
print(int2('1000000', base=10)) # 这里 base 变成了 10,覆盖了已设的默认值 2。 结果为:1000000
print(int2('100', 10)) # 报错,10 前未加 base=,不能分辨这是传给 base 的

本文通过具体示例展示了Python中偏函数的使用方法及其在不同场景下的应用,包括对象方法调用和函数参数预设,旨在帮助读者理解并掌握偏函数的灵活运用。
975

被折叠的 条评论
为什么被折叠?



