gpt4 book ai didi

包含奇怪对象数组的 Python 对象

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

<分区>

Possible Duplicate:
Static class variables in Python
Python OOP and lists

只是想知道我是否可以在这方面得到一些帮助。

我正在使用 python,并且遇到了一个障碍,我似乎无法用我正在处理的小程序弄清楚。这是我的问题(使用一个非常简单且不相关的示例):我有一个类:

class dog:
name = ''
friends = []

我用它做了几个对象:

fido = dog()
rex = dog()

这就是我卡住的地方。我不知道为什么会这样,我还没弄明白。我假设我对某些事情的理解是有缺陷的,任何解释都会很好。所以这是我的问题,如果我将一个对象附加到另一个对象(看起来应该可以正常工作):

fido.friends.append(rex)

...事情搞砸了。正如您在这里看到的:

>>> fido.friends.append(rex)
>>> fido.friends
[<__main__.dog instance at 0x0241BAA8>]
>>> rex.friends
[<__main__.dog instance at 0x0241BAA8>]
>>>

这对我来说毫无意义。不应该只有 fido.friends 里面有东西吗?即使我创建了一个新对象:

rover = dog()

它有一个狗实例,我们可以看到它是我们的“rex”对象。

>>> rex.name = "rex"
>>> fido.friends[0].name
'rex'
>>> rex.friends[0].name
'rex'
>>> rover.friends[0].name
'rex'
>>>

这完全没有意义,我希望得到一些帮助。我四处搜寻了一段时间,试图找到一个解释,但没有找到。对不起,如果我错过了类似的问题。

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