超类的实例变量的值在子类的各个实例之间均保持不变 [英] Values of instance variables of superclass persist across instances of subclass

查看:65
本文介绍了超类的实例变量的值在子类的各个实例之间均保持不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我在Python中使用OOP的方式而言,我不确定这是否是一个基本的误解,但我看到了一些极其奇怪的行为.这是一个代码段:

I'm not sure if this is a fundamental misunderstanding on my part of the way that OOP in Python works, but I'm seeing some extremely strange behavior. Here's a code snippet:

class Foo(object):
    def __init__(self, l = []):
        print "Foo1:", l
        self.mylist = l
        print "Foo2:", self.mylist

class Bar(Foo):
    def __init__(self, label=None):

        self.label = label
        super(Bar, self).__init__()
        print "Bar:", self.mylist



bar1 = Bar()
bar1.mylist.append(4)

bar2 = Bar()
print "bar2's list:", bar2.mylist

我希望在构造bar2时,其mylist实例变量将被设置为空列表.但是,当我在Python 2.6.6中运行该程序时,得到以下输出:

I expect that when bar2 is constructed, its mylist instance variable will be set to the empty list. However, when I run this program in Python 2.6.6, I get the following output:

Foo1: []
Foo2: []
Bar: []
Foo1: [4]
Foo2: [4]
Bar: [4]
bar2's list: [4]

看起来Foo的mylist实例变量正在Bar类的多个实例中持久保存,但是我不知道为什么会这样.你们能给我的任何帮助将不胜感激.

It looks like Foo's mylist instance variable is being persisted across multiple instances of the Bar class, but I have no idea why that would be. Any help you guys could give me would be greatly appreciated.

推荐答案

问题在于默认参数是在模块初始化时绑定的,而不是在函数调用时绑定的,因此只有一个默认列表被共享为该功能的所有调用.

The problem is that default parameters are bound at module initialization time, not at function invocation time, so there is only one default list that gets shared as the default for all invocations of that function.

您真正想做的是:

def __init__(self, l=None):
    if l is None:
        l = []
    self.mylist = l

这篇关于超类的实例变量的值在子类的各个实例之间均保持不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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