当通过解包参数调用函数时,它似乎会增加两次递归深度.我想知道为什么会这样.
一般:
depth = 0
def f():
global depth
depth += 1
f()
try:
f()
except RuntimeError:
print(depth)
#>>> 999
Run Code Online (Sandbox Code Playgroud)
通过拆包电话:
depth = 0
def f():
global depth
depth += 1
f(*())
try:
f()
except RuntimeError:
print(depth)
#>>> 500
Run Code Online (Sandbox Code Playgroud)
理论上两者都应达到1000左右:
import sys
sys.getrecursionlimit()
#>>> 1000
Run Code Online (Sandbox Code Playgroud)
这发生在CPython 2.7和CPython 3.3上.
在PyPy 2.7和PyPy 3.3上存在差异,但它要小得多(1480 vs 1395和1526 vs 1395).
从反汇编中可以看出,除了调用类型(CALL_FUNCTIONvs CALL_FUNCTION_VAR)之外,两者之间几乎没有区别:
import dis
Run Code Online (Sandbox Code Playgroud)
def f():
f()
dis.dis(f)
#>>> 34 0 LOAD_GLOBAL 0 (f)
#>>> 3 CALL_FUNCTION 0 (0 positional, …Run Code Online (Sandbox Code Playgroud) 我想编写一个可以很好地处理数字和运算符的类,所以我想知道当左手参数是内置类型或其他我无法修改实现的值时如何重载运算符.
class Complex(val r:Double,val i:Double){
def +(other:Complex) = new Complex(r+other.r,i+other.i)
def +(other:Double) = new Complex(r+other,i)
def ==(other:Complex) = r==other.r && i==other.i
}
Run Code Online (Sandbox Code Playgroud)
通过此示例,以下工作:
val c = new Complex(3,4)
c+2 == new Complex(5,4) //true
Run Code Online (Sandbox Code Playgroud)
但我也希望能够写作
2+c
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为Int.+不能接受类型的参数Complex.有没有办法让我写这个并让它按我想要的方式工作?
我发现了关于正确的关联方法,但它们似乎需要不同的运算符名称.