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

查看:22
本文介绍了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)

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

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天全站免登陆