根据 this site函数调用优先于让我感到困惑的属性访问。
>>> class cls:
def func(self):
print("Method")
>>> def func():
print("Global Func")
>>> obj=cls()
>>> obj.func() #1
Method
>>> (obj.func)() #2
Method
>>> obj.(func()) #3
SyntaxError: invalid syntax
3 是预期的语法错误,但如果函数调用优先于属性访问,为什么 1 和 2 会产生相同的结果?
最佳答案
根据它链接到的官方 Python 文档,该网站略有错误:https://docs.python.org/3/reference/expressions.html#operator-precedence
您会注意到 Python 文档中列出的运算符优先级在表中的倒数第二个位置都在同一行:x[index]
, x[ index:index]
, x(arguments...)
, x.attribute
.正如文档所述,
Operators in the same box have the same precedence. ... Operators in the same box group left to right (except for exponentiation, which groups from right to left).
无论出于何种原因,您链接到的网站都说相同,只是将这四样东西按顺序排列,而不是放在同一个框中。
关于python - 函数调用运算符优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57245810/