python默认参数的问题....

h_heo 2018-05-03 04:13:15

def a(x,l = []):
""" 实际上不建议用可变类型来传参"""
if x not in l:
l.append(x)
print(locals())
return l
print(locals())
return l

print(a(1))
print(a(2))
print(a(3))
print(a(6, [1,5,6,6,65,8]))
print(a(4))



# 结果 :

{'l': [1], 'x': 1}
[1]
{'l': [1, 2], 'x': 2}
[1, 2]
{'l': [1, 2, 3], 'x': 3}
[1, 2, 3]
{'l': [1, 5, 6, 6, 65, 8], 'x': 6}
[1, 5, 6, 6, 65, 8]
{'l': [1, 2, 3, 4], 'x': 4} # 这里的l为什么又指回原来的了, 为什么呢???
[1, 2, 3, 4]


请教大神们,给我解释下最后那个输入结果 谢谢!!刚刚来论坛学习,没什么积分,请见谅!!
...全文
207 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
h_heo 2018-05-03
  • 打赏
  • 举报
回复
引用 1 楼 hbu_pig 的回复:
你已经可以理解可变的参数会在多次调用时累计。 那就好办了。你显示调用传l列表给它它就用你传的参数。不传参数就还是用默认参数。且可变的默认参数只初始化一次。
python 的官方解释资源在哪里有资源学习,可以分享下么 谢谢
h_heo 2018-05-03
  • 打赏
  • 举报
回复
还想问下,你是怎么知道这些官方解释的,哪里有这些资源学习呢?可以分享下么
h_heo 2018-05-03
  • 打赏
  • 举报
回复
引用 2 楼 hbu_pig 的回复:
因为default value只初始化一次。列表又正好是可变的。 官网是这么解释的 Why are default values shared between objects? This type of bug commonly bites neophyte programmers. Consider this function:
def foo(mydict={}):  # Danger: shared reference to one dict for all calls
    ... compute something ...
    mydict[key] = value
    return mydict
The first time you call this function, mydict contains a single item. The second time, mydict contains two items because when foo() begins executing, mydict starts out with an item already in it. It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object. By definition, immutable objects such as numbers, strings, tuples, and None, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion. Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use None as the default value and inside the function, check if the parameter is None and create a new list/dictionary/whatever if it is. For example, don’t write:
def foo(mydict={}):
    ...
but:
def foo(mydict=None):
    if mydict is None:
        mydict = {}  # create a new dict for local namespace
This feature can be useful. When you have a function that’s time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called “memoizing”, and can be implemented like this:
# Callers will never provide a third parameter for this function.
def expensive(arg1, arg2, _cache={}):
    if (arg1, arg2) in _cache:
        return _cache[(arg1, arg2)]

    # Calculate the value
    result = ... expensive computation ...
    _cache[(arg1, arg2)] = result           # Store result in the cache
    return result
You could use a global variable containing a dictionary instead of the default value; it’s a matter of taste.
谢谢你的回复,谢谢 学习了
欢乐的小猪 2018-05-03
  • 打赏
  • 举报
回复
因为default value只初始化一次。列表又正好是可变的。 官网是这么解释的 Why are default values shared between objects? This type of bug commonly bites neophyte programmers. Consider this function:
def foo(mydict={}):  # Danger: shared reference to one dict for all calls
    ... compute something ...
    mydict[key] = value
    return mydict
The first time you call this function, mydict contains a single item. The second time, mydict contains two items because when foo() begins executing, mydict starts out with an item already in it. It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object. By definition, immutable objects such as numbers, strings, tuples, and None, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion. Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use None as the default value and inside the function, check if the parameter is None and create a new list/dictionary/whatever if it is. For example, don’t write:
def foo(mydict={}):
    ...
but:
def foo(mydict=None):
    if mydict is None:
        mydict = {}  # create a new dict for local namespace
This feature can be useful. When you have a function that’s time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called “memoizing”, and can be implemented like this:
# Callers will never provide a third parameter for this function.
def expensive(arg1, arg2, _cache={}):
    if (arg1, arg2) in _cache:
        return _cache[(arg1, arg2)]

    # Calculate the value
    result = ... expensive computation ...
    _cache[(arg1, arg2)] = result           # Store result in the cache
    return result
You could use a global variable containing a dictionary instead of the default value; it’s a matter of taste.
欢乐的小猪 2018-05-03
  • 打赏
  • 举报
回复
你已经可以理解可变的参数会在多次调用时累计。 那就好办了。你显示调用传l列表给它它就用你传的参数。不传参数就还是用默认参数。且可变的默认参数只初始化一次。

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧