The default values of Defining Functions

The default values are evaluated at the point of function definition in the defining scope, so that

i = 5

def f(arg=i):
    print(arg)

i = 6
f()  # will print 5

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

# This will print
[1]
[1,2]
[1,2,3]

If you don't want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,299评论 3 20
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,514评论 0 13
  • 清晨的阳光, 透过你明亮的眸子, 倒映着我们青涩的笑容。 围墙上的爬山虎, 沿着两行歪歪斜斜的印记肆意伸展。 你说...
    简之游阅读 148评论 0 2
  • 想知道梨子的味道,就得尝。想知道理论的效果,就得用。经李善友介绍多元思维模型,又买了查理芒格《穷查理宝典》。他们提...
    Ken_LC阅读 252评论 0 0