Odd Behaviour Of Python's Class
Solution 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:
classTxdTest(object):
def__init__(self, name = '', atrributes = None):
self.name = name
if attributes isNone
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.
Solution 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.
Solution 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.)
Post a Comment for "Odd Behaviour Of Python's Class"