Python对象的初始化错误。还是我误解对象是如何工作的? [英] Python object initialization bug. Or am I misunderstanding how objects work?

查看:149
本文介绍了Python对象的初始化错误。还是我误解对象是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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)

这将打印参考分配给 one._resources 有一个和<$ C $对象C>两个的对象。我认为两个将是一个空数组,因为它显然是将其设置为这样的,如果在创建对象时,它没有定义。取消注释 MyObj中.__的init __(个体经营,资源)做同样的事情。使用超(分机,个体经营).__的init __(资源)也做同样的事情。

This will print the reference to the object assigned to one._resources for both one and two objects. I would think that two would be an empty array as it is clearly setting it as such if it's not defined when creating the object. Uncommenting myobj.__init__(self, resources) does the same thing. Using super(ext, self).__init__(resources) also does the same thing.

我可以让它开始工作的唯一方法是,如果我使用以下命令:

The only way I can get it to work is if I use the following:

two = ext(dummy(2))

我不应该创建对象使这项工作时手动设置的默认值。或者,也许我做的。有什么想法?

I shouldn't have to manually set the default value when creating the object to make this work. Or maybe I do. Any thoughts?

这个我试过使用Python 2.5和2.6。

I tried this using Python 2.5 and 2.6.

推荐答案

您应该更改

def __init__(self, resources=[]):
    self._resources = resources

def __init__(self, resources=None):
    if resources is None:
        resources = []
    self._resources = resources

和一切会更好。这是如果他们是可变的默认参数处理方式的细节。有一个在此页面讨论部分的更多信息。

and all will be better. This is a detail in the way default arguments are handled if they're mutable. There's some more information in the discussion section of this page.

这篇关于Python对象的初始化错误。还是我误解对象是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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