gpt4 book ai didi

Python 基类共享属性?

转载 作者:太空狗 更新时间:2023-10-29 18:19:42 25 4
gpt4 key购买 nike

<分区>

test.py 中的代码:

class Base(object):
def __init__(self, l=[]):
self.l = l

def add(self, num):
self.l.append(num)

def remove(self, num):
self.l.remove(num)

class Derived(Base):
def __init__(self, l=[]):
super(Derived, self).__init__(l)

Python shell session :

Python 2.6.5 (r265:79063, Apr  1 2010, 05:22:20) 
[GCC 4.4.3 20100316 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> a = test.Derived()
>>> b = test.Derived()
>>> a.l
[]
>>> b.l
[]
>>> a.add(1)
>>> a.l
[1]
>>> b.l
[1]
>>> c = test.Derived()
>>> c.l
[1]

我期待的是“类 C++”行为,其中每个派生对象都包含其自己的基类实例。现在还是这样吗?为什么每个对象似乎共享同一个列表实例?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com