It is a common mistake in Python until you get the way it works, and
them learn to avoid this intuitivelly.
The problem is that the default parameter to the __init__
method
wordlist
, which is am empty list denoted by [ ]
is created just once,
when the class body is parsed.
After that, each invocation to the __init__
method (made automatically
at object instantiation) passes the same object - the single empty list -
as parameter to the function. Therefore, in the example above, all instances of
Node
will point to the same list- which is the problem you detected.
The correct pattern to avoid the problem is like this:
class Node(object):
def __init__(self,wordList=None):
if wordlist is None: wordlist = []
self.wordList = wordList
This way, a new empty ist is created at each __init__
invocation.