Python对象包含奇怪的对象数组 [英] Python object containing an array of objects being weird

查看:61
本文介绍了Python对象包含奇怪的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python中的静态类变量

Python OOP和列表

只是想知道我是否可以对此有所帮助。

just wondering if I could get some help on this.

我正在使用python,但是遇到了一个障碍,我似乎无法通过我正在开发的一个小程序弄清楚它。这是我的问题(使用一个非常简单且不相关的示例):我有一个班级:

I am using python, and have hit an obstacle that I can't seem to figure out with a small program I am working on. Here is my problem (using a very simple and unrelated example): I have a class:

class dog:
    name = ''
    friends = []

我用它制作了几个对象:

I make a couple objects from it:

fido = dog()
rex = dog()

这就是我遇到的问题。我不知道为什么会这样,我还没有弄清楚。我假设我对某些东西的理解不足,但任何解释都很好。所以这是我的问题,如果我将一个对象附加到另一个对象(看起来应该可以正常工作):

And here is where I get stuck. I don't know why this is happening and I haven't figured it out. I'm assuming my understanding of something is deficient though, any explanation would be great. So here is my problem, if I append one object to the other (which seems like it should work just fine):

fido.friends.append(rex)

...事情搞砸了。如您所见:

... things mess up. As you can see here:

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

这对我来说是没有意义的。不仅fido.friends里面应该有东西吗?即使我创建了新对象:

That just deosn't make sense to me. Shouldn't only fido.friends have something in it? Even if I make a new object:

rover = dog()

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

It has a dog instance in it, which we can see is our 'rex' object.

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

这只是没有道理,我希望能提供一些帮助。我搜寻了片刻,试图找到一个解释,但是没有找到。抱歉,如果我错过了类似的问题。

This just isn't making sense, and I'd love some help. I searched around for awhile trying to find an explanation, but didn't. Sorry if there is a similar question I missed.

推荐答案

如果每条狗都有自己的 列表的朋友,必须使用 instance 属性:

If each dog should have his own list of friends, you must use instance attributes:

class Dog(object):

    family = 'Canidae' # use class attributes for things all instances share 

    def __init__(self, name):
        """ constructor, called when a new dog is instantiated """
        self.name = name
        self.friends = []

    def __repr__(self):
        return '<Dog %s, friends: %s>' % (self.name, self.friends)

fido = Dog('fido')
rex = Dog('rex')

fido.friends.append(rex)
print(fido) # <Dog fido, friends: [<Dog rex, friends: []>]>

您使用的是类属性(该值在实例之间共享)。

What you used were class attributes (the value is shared among instances). More on this:

  • http://www.diveintopython.net/object_oriented_framework/class_attributes.html

这篇关于Python对象包含奇怪的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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