为什么类方法会在 python 类方法类型提示中隐藏外部作用域的名称?

问题描述 投票:0回答:1

例如:

In [4]: In [17]: class X:
   ...:     def not_shadow(self, x: list[int]):
   ...:         pass
   ...: 
   ...:     def list(self):
   ...:          list()
   ...: 
   ...:     def shadow_by_X_list_method(self, x: list[int]):
   ...:         pass
   ...: 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 class X:
      2     def not_shadow(self, x: list[int]):
      3         pass

Cell In[4], line 8, in X()
      5 def list(self):
      6      list()
----> 8 def shadow_by_X_list_method(self, x: list[int]):
      9     pass

TypeError: 'function' object is not subscriptable

我预计类函数名称只能作为 self 变量的成员使用。

python annotations type-hinting
1个回答
0
投票

这是范围规则的一个怪癖!

虽然可能令人惊讶,正如 @jonsharpe 在评论中指出的那样,这种行为与 Python 中的任何地方都是相同的,并且允许后面的方法及其参数引用早期的方法一般来说

在他们的示例中,他们注意到

@property
,它将附加方法直接添加到包装的方法中

摘自文档https://docs.python.org/3/library/functions.html#property.getter

class Foo:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter            # <-- property of earlier x
    def x(self, value):
        self._x = value
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.