看看我的PYTHON
def add(x, y):return x + y
import functools
print(functools.reduce(add, ))
print(functools.reduce(lambda x,y:x*y, range(1, 11)))
square = functools.partial(pow, exp=2)
print(square(2))
cube = functools.partial(pow, exp=3)
print(cube(3))
import time
import functools
def time_master(func):
@functools.wraps(func)
def call_func():
print("开始运行程序...")
start = time.time()
func()
stop = time.time()
print("结束程序运行...")
print(f"一共耗费了 {(stop-start):.2f} 秒")
return call_func
def myfunc():
time.sleep(2)
print("I love FishC.")
myfunc = time_master(myfunc)
myfunc() 鱼油,你的代码整体思路不错,但有一个地方会直接报错:
print(functools.reduce(add, )) 这里 reduce 只传了函数,没有传可迭代对象,会抛出 TypeError。
应该写成类似这样:
print(functools.reduce(add, ))
其他部分基本可以运行,但有两个小建议:
1. functools.partial(pow, exp=2) 依赖 Python 版本支持 pow 的关键字参数 exp。更稳妥的写法是固定位置参数,例如:
square = functools.partial(pow, 2)
print(square(3))# 2 的 3 次方
不过你原本的写法在 Python 3.8+ 通常也能跑。
2. 装饰器 time_master 里的 call_func 没有接收参数,如果以后装饰带参数的函数会出错。建议改成:
def call_func(*args, **kwargs):
...
func(*args, **kwargs)
...
修正后的完整代码可以参考:
import functools
import time
def add(x, y):
return x + y
print(functools.reduce(add, ))
print(functools.reduce(lambda x, y: x * y, range(1, 11)))
square = functools.partial(pow, exp=2)
print(square(2))
cube = functools.partial(pow, exp=3)
print(cube(3))
def time_master(func):
@functools.wraps(func)
def call_func(*args, **kwargs):
print("开始运行程序...")
start = time.time()
func(*args, **kwargs)
stop = time.time()
print("结束程序运行...")
print(f"一共耗费了 {(stop - start):.2f} 秒")
return call_func
def myfunc():
time.sleep(2)
print("I love FishC.")
myfunc = time_master(myfunc)
myfunc()
这样就能正常运行啦,继续加油!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 我感觉我一直在发表 贝尔0703 发表于 2026-09-27 12:56
我感觉我一直在发表
哈哈,你说的“发表”是不是指 print 呀?在 Python 里 print 就是把内容输出到屏幕,确实有点像在“发表”。
你代码里 print 用了不少次,所以会有一种“一直在发表”的感觉。如果想让输出清爽一点,可以先把结果存起来,最后统一 print:
import functools
def add(x, y):
return x + y
result1 = functools.reduce(add, )
result2 = functools.reduce(lambda x, y: x * y, range(1, 11))
print(result1, result2)
不过注意,functools.reduce(add, ) 这里还是缺了可迭代对象,会报错哦。记得补上类似 这样的参数。
继续加油,多发“有用的表”!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 谢谢 贝尔0703 发表于 2026-09-27 12:56
谢谢
不客气,鱼油!
继续加油,有问题随时来问~
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 {:10_256:} 某一个“天” 发表于 2026-9-27 19:03
干嘛哩
页:
[1]