|
|
发表于 2026-9-27 12:54:36
|
显示全部楼层
鱼油,你的代码整体思路不错,但有一个地方会直接报错:
print(functools.reduce(add, )) 这里 reduce 只传了函数,没有传可迭代对象,会抛出 TypeError。
应该写成类似这样:
- print(functools.reduce(add, [1, 2, 3, 4]))
复制代码
其他部分基本可以运行,但有两个小建议:
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, [1, 2, 3, 4]))
- 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 小助理,如未能正确解答您的问题,请继续追问。 |
|