【问题标题】:Python object containing an array of objects being weird [duplicate]包含奇怪对象数组的Python对象[重复]
【发布时间】:2012-12-20 03:14:03
【问题描述】:

可能重复:
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()

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

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

这只是没有意义,我希望得到一些帮助。我搜索了一段时间试图找到一个解释,但没有。抱歉,如果我错过了类似的问题。

【问题讨论】:

    标签: python class object


    【解决方案1】:

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

    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(值在实例之间共享)。更多信息:

    【讨论】:

    • 哇,谢谢 miku!非常感谢您快速、良好的回答。
    【解决方案2】:

    在类内部声明的变量,未附加到实例,是 python 中的static 变量。

    【讨论】:

    • “静态”不是 Python 用来区分这些概念的词。
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      实现您想要做的事情的正确方法是使用__init__ 方法:

      >>> class dog:
             def __init__(self):
                 self.f = []
      
      
      >>> a = dog()
      >>> b = dog()
      >>> a.f.append(b)
      >>> a.f
      [<__main__.dog instance at 0x02DA6F08>]
      >>> c = dog()
      >>> c.f
      []
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-15
        • 2020-11-29
        • 2016-05-12
        • 1970-01-01
        相关资源
        最近更新 更多