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

2024-05-28 20:52:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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>]
>>> 

那对我来说毫无意义。难道不应该只有菲多。朋友们有什么东西在里面吗?即使我做了一个新的物体:

rover = dog()

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

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

这没道理,我很想得到帮助。我到处找了一会儿,想找到一个解释,但没有找到。对不起,如果有一个类似的问题我错过了。


Tags: 对象instancenamemainfido事情atclass
3条回答

类内声明的变量(未附加到实例)是python中的static变量。

如果每只狗都有自己的朋友列表,则必须使用实例属性:

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: []>]>

您使用的是class attributes(值在实例之间共享)。更多信息:

为了避免这种情况,请将变量声明放在__init__函数中,如下所示:

class Dog:
    def __init__(self):
        self.name = ''
        self.friends = []

相关问题 更多 >

    热门问题