Bug?? reusing objects
Hans Nowak
wurmy at earthlink.net
Sun May 26 00:52:02 EDT 2002
Damian Menscher wrote:
>
> The following test program demonstrates what I believe is a bug:
> -------------------------------------------------------------
> #!/tmp/Python-2.2.1/python
>
> class foobar:
> def __init__(self, string=[]):
> self.data = string
> def add(self, new=""):
> self.data.append(new)
>
> a = foobar("foo")
> print a.data
>
> a = foobar("bar")
> print a.data
>
> a = foobar()
> print a.data
>
> a.add("foo")
> a.add("bar")
> print a.data
>
> a = foobar()
> print a.data ### returns ['foo', 'bar'] for me
> ### I'd expect it to return []
> -------------------------------------------------------------
> If this is expected behavior, could someone please explain it?
> Otherwise, I'll be happy to file a bug report.
It's a FAQ:
http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.025.htp
"It is often expected that a function CALL creates new objects
for default values. This is not what happens. Default values
are created when the function is DEFINED, that is, there is
only one such object that all functions refer to. If that
object is changed, subsequent calls to the function will refer
to this changed object. By definition, immutable objects
(like numbers, strings, tuples, None) are safe from change.
Changes to mutable objects (like dictionaries, lists, class
instances) is what causes the confusion."
--
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
More information about the Python-list
mailing list