在类实例初始化时,Python列表应该为空,但事实并非如此.为什么? [英] Python list should be empty on class instance initialisation, but it's not. Why?

查看:63
本文介绍了在类实例初始化时,Python列表应该为空,但事实并非如此.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类的实例,该实例包含默认情况下为空的列表;而不是稍后将此列表设置为最终的完整列表,我想依次向其中添加项目.这是一段示例代码,说明了这一点:

I would like to create instances of a class containing a list that's empty by default; instead of later setting this list to the final full list I would like to successively add items to it. Here's a piece of sample code illustrating this:

#!/usr/bin/python

class test:
    def __init__(self, lst=[], intg=0):
        self.lista   = lst
        self.integer = intg

name_dict = {}
counter   = 0

for name in ('Anne', 'Leo', 'Suzy'):
    counter += 1

    name_dict[name] = test()
    name_dict[name].integer += 1
    name_dict[name].lista.append(counter)

    print name, name_dict[name].integer, name_dict[name].lista

运行上述程序时,我希望得到

When I ran the above program I expected to get

Anne 1 [1]
狮子座1 [2]
Suzy 1 [3]

Anne 1 [1]
Leo 1 [2]
Suzy 1 [3]

我假设 lista 总是被初始化为一个空列表.

as I assumed lista to always be initialised to an empty list.

我得到的是这个:

Anne 1 [1]
狮子座1 [1,2]
Suzy 1 [1、2、3]

Anne 1 [1]
Leo 1 [1, 2]
Suzy 1 [1, 2, 3]

如果我将 self.lista = lst 替换为 self.lista = [] ,则效果很好,就像我添加行 name_dict [name].lista = [] 到for循环.

If I replace self.lista = lst by self.lista = [] it works fine, just like when I add the line name_dict[name].lista = [] to the for loop.

为什么保留了先前对象列表的内容,却没有保留它们的 integer 值?我对Python相当陌生,所以如果有人能指出我的想法/假设误入歧途,那将是很棒的事情.

Why is it that the contents of the previous objects' lists are retained, yet their values of integer aren't? I am rather new to Python, so it would be great if someone could point out to me where my thoughts/assumptions have gone astray.

非常感谢您的答复.

推荐答案

使用可变对象作为默认值是一个非常糟糕的主意,就像您在这里所做的那样:

It is a very bad idea to use a mutable object as a default value, as you do here:

def __init__(self, lst=[], intg=0):
     # ...

将其更改为此:

def __init__(self, lst=None, intg=0):
     if lst is None:
         lst = []
     # ...

您的版本无法正常运行的原因是,在定义函数时仅创建一次空列表,而不是在每次调用函数时都会创建空列表.

The reason that your version doesn't work is that the empty list is created just once when the function is defined, not every time the function is called.

在某些 Python 实现中,您可以通过检查 func_defaults 的值来查看函数默认值的值:

In some Python implementations you can see the value of the default values of the function by inspecting the value of func_defaults:

print test.__init__.func_defaults
name_dict[name] = test()
# ...

输出:


([],)
Anne 1 [1]
([1],)
Leo 1 [1, 2]
([1, 2],)
Suzy 1 [1, 2, 3] 

这篇关于在类实例初始化时,Python列表应该为空,但事实并非如此.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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