为什么在成员变量上使用海象运算符会引发 SyntaxError?
Why does using the walrus operator on a member variable raise a SyntaxError?
为什么我不能使用海象运算符 :=
来分配属性?它在分配给局部变量时有效:
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 = []
有点啰嗦,但是这意味着海象运算符不支持属性赋值。
您遇到的错误也非常特定于具体情况,验证这一点(“不能将赋值表达式与属性一起使用”的意思是“不能使用海象运算符设置属性”)。
为什么我不能使用海象运算符 :=
来分配属性?它在分配给局部变量时有效:
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 = []
有点啰嗦,但是这意味着海象运算符不支持属性赋值。
您遇到的错误也非常特定于具体情况,验证这一点(“不能将赋值表达式与属性一起使用”的意思是“不能使用海象运算符设置属性”)。