Python对象初始化错误.或者我误解了对象是如何工作的?

1 python arguments mutable

  1 import sys
  2 
  3 class dummy(object):
  4     def __init__(self, val):
  5         self.val = val
  6 
  7 class myobj(object):
  8     def __init__(self, resources):
  9         self._resources = resources
 10 
 11 class ext(myobj):
 12     def __init__(self, resources=[]):
 13         #myobj.__init__(self, resources)
 14         self._resources = resources
 15 
 16 one = ext()
 17 one._resources.append(1)
 18 two = ext()
 19 
 20 print one._resources
 21 print two._resources
 22 
 23 sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

这将打印的参考对象分配one._resources两个onetwo对象.我认为这two将是一个空数组,因为如果在创建对象时没有定义它,它就会明确地设置它.取消注释也会myobj.__init__(self, resources)做同样的事情.使用super(ext, self).__init__(resources)也做同样的事情.

我可以使用它的唯一方法是使用以下方法:

two = ext(dummy(2))
Run Code Online (Sandbox Code Playgroud)

我不必在创建对象时手动设置默认值以使其工作.或者我也许.有什么想法吗?

我尝试使用Python 2.5和2.6.

Pet*_*ter 7

你应该改变

def __init__(self, resources=[]):
    self._resources = resources
Run Code Online (Sandbox Code Playgroud)

def __init__(self, resources=None):
    if resources is None:
        resources = []
    self._resources = resources
Run Code Online (Sandbox Code Playgroud)

一切都会好起来的.这是默认参数处理方式的细节,如果它们是可变的.本页的讨论部分提供了更多信息.

  • +1:不要将可变对象(如列表)用作方法函数定义中的默认值.这是标准的n00b错误. (3认同)

Ant*_*sma 6

您的问题是在函数定义时评估默认值.这意味着实例之间共享相同的列表对象.有关更多讨论,请参阅此问题的答案.