Odd behaviour of python's class [duplicate]

不想你离开。 提交于 2019-12-11 10:26:46

问题


Here is a python class:

class TxdTest(object):
    def __init__(self, name = '', atrributes = []):
        self.name = name
        self.attributes = atrributes

and then I use it like this:

def main():
    for i in range(3):
        test = TxdTest()
        print test.name
        print test.attributes
        test.name = 'a'
        test.attributes.append(1)

so, what's the result? The result is:

[]

[1]

[1, 1]

Why the 'self.attributes' in class still obtain the value ?


回答1:


When passing a mutable object (like a list) to a function or method in python, a single object is used across all invocations of the function or method. This means that ever time that function or method (in this case, your __init__ method) is called, the exact same list is used every time, holding on to modifications made previously.

If you want to have an empty list as a default, you should do the following:

class TxdTest(object):
    def __init__(self, name = '', atrributes = None):
        self.name = name
        if attributes is None
             self.attributes = []
        else:
             self.attributes = attributes

For a detailed explanation of how this works see: “Least Astonishment” in Python: The Mutable Default Argument, as mentioned by bgporter.




回答2:


Short answer: there's only one list, because it is assigned when the function is defined not when it's called. So all instances of the class use the same attributes list.

Nothing to do with classes; the problem occurs whenever you use a mutable object as a default value in a function argument list.




回答3:


This is one of the "Python Pitfalls" described here: http://zephyrfalcon.org/labs/python_pitfalls.html

(You'll want #2 and #5. The article is from 2003, but it still applies to modern Python versions.)



来源:https://stackoverflow.com/questions/8145971/odd-behaviour-of-pythons-class

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