为什麽我无法在已有 `list` 方法的类中输入 `list` 参数

-5 投票
1 回答
67 浏览
提问于 2025-04-14 18:28

我正在使用Python 3.10,并且有一个类(我简化了一下):

class Greetings:
    def list(self) -> list[str]:
        return ['ab', 'cd']

    def hello(self, names: list[str]) -> None:
        for name in names:
            print("Hello", name)

在测试这个类的时候,我遇到了这个错误:

... in Greetings
    def hello(self, names: list[str]) -> None:
E   TypeError: 'function' object is not subscriptable` error.

我知道问题出在我的 list 方法上,Python 在尝试使用它来定义 names 参数的类型。但是我不明白为什么会这样,或者这是不是Python语言本身的问题。根据我的理解,从Python 3.10开始,我可以直接使用 list 来定义类型,而不需要从 typing 模块中导入 List

有人能猜到原因吗?

1 个回答

2

在你定义了 def list 之后,在你的 class 块里面,名字 list 就指的是你刚刚定义的那个 def list 方法。这样一来,你就把这个名字给覆盖掉了。要解决这个问题,你可以给 list 起个别名,或者使用 builtins 里的内容:

import builtins

class Greetings:
    ...

    def hello(self, names: builtins.list[str]) -> None:
        ...

撰写回答