Python函数中的默认值 [英] Default value in a function in Python

查看:84
本文介绍了Python函数中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到以下内容:

  class c:
def __init __(self,data = []) :
self._data = data
a = c()
b = c()
a._data.append(1)
print b._data
[1]

这是正确的行为吗?

解决方案

是的,这是正确的行为。



但是,从您的问题来看,这似乎不是您所期望的。 / p>

如果您希望它符合您的期望,请注意以下几点:



规则1.请勿使用可变对象作为默认值。

  def anyFunction(arg = []):

不会创建新的列表对象。 arg 的默认列表对象将在所有位置共享。



类似地

  def anyFunction(arg = {}):

不会创建新的字典对象。此默认字典将被共享。

  class MyClass(object):
def __init __(self,arg = None) :
self.myList = []如果arg为None arg

提供默认参数值,它是一个新鲜的空列表对象。


I am noticing the following:

class c:
  def __init__(self, data=[]):
    self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]

Is this the correct behavior?

解决方案

Yes, it's correct behavior.

However, from your question, it appears that it's not what you expected.

If you want it to match your expectations, be aware of the following:

Rule 1. Do not use mutable objects as default values.

def anyFunction( arg=[] ):

Will not create a fresh list object. The default list object for arg will be shared all over the place.

Similarly

def anyFunction( arg={} ):

will not create a fresh dict object. This default dict will be shared.

class MyClass( object ):
    def __init__( self, arg= None ):
        self.myList= [] if arg is None else arg 

That's a common way to provide a default argument value that is a fresh, empty list object.

这篇关于Python函数中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆