gpt4 book ai didi

python - 为什么在成员变量上使用 walrus 运算符会引发 SyntaxError?

转载 作者:行者123 更新时间:2023-12-03 22:59:13 25 4
gpt4 key购买 nike

为什么我不能使用海象运算符 :=分配给一个属性?它在分配给局部变量时起作用:

my_eyes = ["left", "right"]
if saved_eye := my_eyes.index("left"):
print(saved_eye)

# outputs >>> 0
但是,如果我尝试分配给对象属性,则会出现语法错误:
class MyEyes:
def __init__(self):
self.eyes = ["left", "right"]
self.saved_eye = None

def ohyes(self):
if self.saved_eye := self.eyes.index("left"):
print(self.saved_eye)

x = MyEyes()
x.ohyes()

# raises
# >>> if self.saved_eye := self.eyes.index("left"):
# >>> SyntaxError: cannot use assignment expressions with attribute
我的意思是我可以使用临时局部变量绕过错误,但为什么会发生这种情况?我相信 100% 这是一种合法的语法。

最佳答案

语法是非法的,如 PEP 572 中所述,其中定义了海象运算符(又名“赋值表达式”):

Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions.

Conversely, assignment expressions don't support the advanced features found in assignment statements:

Single assignment targets other than a single NAME are not supported:

# No equivalent
a[i] = x
self.rest = []

这有点罗嗦,但这意味着海象运算符不支持属性赋值。
您遇到的错误也非常特定于这种情况,验证这一点(“不能使用具有属性的赋值表达式”意味着“不能使用海象运算符设置属性”)。

关于python - 为什么在成员变量上使用 walrus 运算符会引发 SyntaxError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67260162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com