我刚刚学到,新的海象运算符 (:=
) 不能用于设置实例属性,这是无效的语法(会引发SyntaxError
)。
为什么? (您能提供官方文档中提到这一点的链接吗?)
我查看了PEP 572,但没有找到这个问题被记录在哪里。
研究
这个答案提到了这个限制,但没有解释或来源:
你不能在对象属性上使用海象运算符
示例代码
class Foo:
def __init__(self):
self.foo: int = 0
def bar(self, value: int) -> None:
self.spam(self.foo := value) # Invalid syntax
def baz(self, value: int) -> None:
self.spam(temp := value)
self.foo = temp
def spam(self, value: int) -> None:
"""Do something with value."""
试图导入Foo
会导致SyntaxError
错误:
self.spam(self.foo := value)
^
SyntaxError: cannot use assignment expressions with attribute