我在Python 3中尝试执行以下MCVE时遇到语法错误。
HEIGHT = 26
WIDTH = 26
OTHERVAR = 5
class Foo():
def __init__(self, OTHERVAR, HEIGHT*WIDTH):
print (str(OTHERVAR + HEIGHT*WIDTH))
foo_inst = Foo()
以下是错误
File "a.py", line 6
def __init__(self, OTHERVAR, HEIGHT*WIDTH):
^
SyntaxError: invalid syntax
我想知道为什么乘法*运算符在这种情况下是无效的语法。
如果有人能解释为什么这是糟糕的语法,并提供一个潜在的解决方案,那就太好了。非常感谢。
函数参数假设为变量,则HEIGHT*WIDTH会生成一个值,而不是变量。
你可能在找这个(默认值(吗?
>>> a = 1
>>> b = 2
>>> def test(c=a*b):
... print(c)
...
>>> test()
2
>>> def test(c=a*b, d):
... print(c, d)
...
File "<stdin>", line 1
SyntaxError: non-default argument follows default argument
>>> def test(d, c=a*b):
... print(d, c)
...
>>> test(10)
(10, 2)
并通过命名参数调用
>>> def test(d, c=a*b, e=20):
... print(d, c, e)
...
>>> test(10, e=30)
(10, 2, 30)