奇怪的语法(继承中的海象运算符)
Odd Syntax (Walrus operator in inheritance)
我正在查看 python 的语法,发现您可以在继承中使用海象运算符!不信,我试了一下:
class foo: pass
class bar(foobar := foo):
def x(self):
print("it works!")
b = bar()
b.x()
这不会引发 any 语法错误 (python 3.8.2)!它的用途是什么,它是如何工作的?
经过一些试验(和运气)后,我发现它用于重命名 类 之类的东西,同时为它们继承:
class foo:
def __init__(self, x):
pass
class bar(foobar := foo):
def __init__(self):
foobar.__init__(self, 2)
def x(self):
print("it works!")
b = bar()
b.x()
如果删除海象运算符,它就不起作用(很明显)。我不确定它到底有什么用。
它没有用 - 所以不要使用它 ;-) 那里允许任意表达式。比如这个就更没用了:
from random import choice
class C(choice([int, list])):
pass
玩得开心 ;-)
What is the use of it, and how does it work?
海象运算符在继承中没有特定的用例。它起作用只是因为 class 是一个表达式,所以它允许表达式允许的所有内容,包括海象运算符。正如评论中指出的那样,您可以使用以下方法获得相同的结果:
foobar = foo
class bar(foobar):
...
表达式中允许的其他内容也同样有效,例如括号和函数调用:
class bar(((foo))):
pass
class bar((lambda x: x)(foo)):
pass
我正在查看 python 的语法,发现您可以在继承中使用海象运算符!不信,我试了一下:
class foo: pass
class bar(foobar := foo):
def x(self):
print("it works!")
b = bar()
b.x()
这不会引发 any 语法错误 (python 3.8.2)!它的用途是什么,它是如何工作的?
经过一些试验(和运气)后,我发现它用于重命名 类 之类的东西,同时为它们继承:
class foo:
def __init__(self, x):
pass
class bar(foobar := foo):
def __init__(self):
foobar.__init__(self, 2)
def x(self):
print("it works!")
b = bar()
b.x()
如果删除海象运算符,它就不起作用(很明显)。我不确定它到底有什么用。
它没有用 - 所以不要使用它 ;-) 那里允许任意表达式。比如这个就更没用了:
from random import choice
class C(choice([int, list])):
pass
玩得开心 ;-)
What is the use of it, and how does it work?
海象运算符在继承中没有特定的用例。它起作用只是因为 class 是一个表达式,所以它允许表达式允许的所有内容,包括海象运算符。正如评论中指出的那样,您可以使用以下方法获得相同的结果:
foobar = foo
class bar(foobar):
...
表达式中允许的其他内容也同样有效,例如括号和函数调用:
class bar(((foo))):
pass
class bar((lambda x: x)(foo)):
pass