|
|
发表于 2026-9-26 16:33:03
|
显示全部楼层
鱼油你好,代码整体思路不错,但有几个地方会报错,帮你梳理一下:
1. times 被重复定义
后面的定义会覆盖前面的。第三次定义里:
- def times(s:list, n:int = 3) -> list:
- return s * n
复制代码
s 没有默认值,所以执行到 print(times()) 时会报:
TypeError: times() missing 1 required positional argument: 's'
程序会在这里停止,后面的代码不会运行。
2. 类型注解不是默认值
s:list 只是提示 s 应该是列表,不会给它默认值。想有默认值要写 s: list = None 或 s: list = [] (可变默认参数要小心)。
3. 最后属性名写错了
应该是双下划线:
- print(times.__name__)
- print(times.__annotations__)
- print(exchange.__doc__)
复制代码
你写成了 _name_、_anotations_、_doc_,会报 AttributeError。另外 annotations 不是 anotations。
4. 建议
如果想分别测试 str、list、dict 版本,用不同函数名,例如 times_str、times_list、times_dict,否则前面的会被覆盖。
修改示例:
- def exchange(dollar, rate=6.32):
- """汇率转换,美元 -> 人民币"""
- return dollar * rate
- print(exchange(20))
- help(exchange)
- def times_str(s: str = "FishC", n: int = 3) -> str:
- return s * n
- def times_list(s: list = None, n: int = 3) -> list:
- if s is None:
- s = []
- return s * n
- def times_dict(s: dict, n: int = 3) -> list:
- return list(s.keys()) * n
- print(times_str())
- print(times_list())
- print(times_dict({'A': 1, 'B': 2, 'C': 3}))
- print(times_str.__name__)
- print(times_str.__annotations__)
- print(exchange.__doc__)
复制代码
这样就能正常跑通并看到效果。类型注解只是提示,不影响实际运行。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|