1

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 ?

Sonny
  • 182
  • 1
  • 1
  • 9

3 Answers3

4

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.

Community
  • 1
  • 1
Wilduck
  • 13,822
  • 10
  • 58
  • 90
  • @Sonny for brevity without loss of readability, consider the ternary operator `self.attributes = list() if attributes is None else attributes` – trianta2 Jul 08 '15 at 18:17
1

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.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

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.)

Hans Nowak
  • 7,600
  • 1
  • 18
  • 18