我很惊讶地发现,在 Python 中,函数参数列表中的类是在定义函数时实例化的,而不是在调用函数时实例化的。
考虑以下代码
class A:
def __init__(self):
print("init method called")
def f(a=A()):
print("function f called")
f()
f()
这将给出以下输出:
init method called
function f called
function f called
因此,该程序中仅构造了一个类 A 的对象,而不是每次调用函数 f 时都构造了一个对象。 为什么会这样?这是解释性语言的共同特征吗?
最佳答案
您可以查看documentation或其他类似主题的问题:
关于python - 为什么 python 在定义时而不是在调用时评估函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57688643/