Hello,
I have written the following script to illustrate a problem in my code:
class BaseClass(object):
def __init__(self):
self.collection = []
class MyClass(BaseClass):
def __init__(self, name, collection=[]):
BaseClass.__init__(self)
self.name = name
Em Sex, 2006-04-14 às 09:18 -0700, wietse escreveu:
def __init__(self, name, collection=[]):
Never, ever, use the default as a list.
self.collection = collection
This will just make a reference of self.collection to the collection
argument.
inst.collection.append(i)
As
Em Sex, 2006-04-14 às 13:30 -0300, Felipe Almeida Lessa escreveu:
To solve your problem, change
def __init__(self, name, collection=[]):
BaseClass.__init__(self)
self.name = name
self.collection = collection # Will reuse the list
to
def __init__(self, name,
On Fri, 14 Apr 2006 13:30:49 -0300, Felipe Almeida Lessa wrote:
Em Sex, 2006-04-14 às 09:18 -0700, wietse escreveu:
def __init__(self, name, collection=[]):
Never, ever, use the default as a list.
Unless you want to use the default as a list.
Sometimes you want the default to mutate
Em Sáb, 2006-04-15 às 04:03 +1000, Steven D'Aprano escreveu:
Sometimes you want the default to mutate each time it is used, for example
that is a good technique for caching a result:
def fact(n, _cache=[1, 1, 2]):
Iterative factorial with a cache.
try:
return _cache[n]