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 ?
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:
For a detailed explanation of how this works see: “Least Astonishment” in Python: The Mutable Default Argument, as mentioned by bgporter.