Python. Strange class attributes behavior

ε祈祈猫儿з 提交于 2019-12-24 08:18:01

问题


>>> class Abcd:

...     a = ''
...     menu = ['a', 'b', 'c']
... 
>>> a = Abcd()
>>> b = Abcd()
>>> a.a = 'a'
>>> b.a = 'b'
>>> a.a
'a'
>>> b.a
'b'

It's all correct and each object has own 'a', but...

>>> a.menu.pop()
'c'
>>> a.menu
['a', 'b']
>>> b.menu
['a', 'b']

How could this happen? And how to use list as class attribute?


回答1:


This is because the way you're initializing the menu property is setting all of the instances to point to the same list, as opposed to different lists with the same value.

Instead, use the __init__ member function of the class to initialize values, thus creating a new list and assigning that list to the property for that particular instance of the class:

class Abcd:
    def __init__(self):
        self.a = ''
        self.menu = ['a', 'b', 'c']



回答2:


See class-objects in the tutorial, and notice the use of self.

Use instance attributes, not class attributes (and also, new style classes) :

>>> class Abcd(object):
...     def __init__(self):
...         self.a = ''
...         self.menu = ['a','b','c']
...         
>>> a=Abcd()
>>> b=Abcd()
>>> a.a='a'
>>> b.a='b'
>>> a.a
'a'
>>> b.a
'b'
>>> a.menu.pop()
'c'
>>> a.menu
['a', 'b']
>>> b.menu
['a', 'b', 'c']
>>> 



回答3:


because variables in Python are just "labels"

both Abcd.menu and a.menu reference the same list object.

in your case you should assign the label to a new object,

not modify the object inplace.

You can run

a.menu = a.menu[:-1]

instead of

a.menu.pop()

to feel the difference



来源:https://stackoverflow.com/questions/2707472/python-strange-class-attributes-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!