python
class foo:
def __init__(self, x=[]):
self.y = x
a = foo()
a.y.append("123456")
a.y
b = foo()
b.y
a.y.append("98765")
a.y
b.y
Try it !!!! It wasn't quite what I've expected.
Go figure.....
python
class foo:
def __init__(self, x=[]):
self.y = x
a = foo()
a.y.append("123456")
a.y
b = foo()
b.y
a.y.append("98765")
a.y
b.y
6 comments:
The better way to do this is to declare the class as follows:
class foo:
....def __init__(self, x=None):
........if x:
............self.y = x
........else:
............self.y = []
Regardless of the right way to do this, it is not immediately obvious why one shouldn't code a class the first way. An explanation of what happens can be found here: http://www.network-theory.co.uk/docs/pytut/tut_28.html
Wow, that's really weird. Not at all what I would have expected. I still like Python, but it definitely has some warts.
Yes,
"the default value is evaluted only once"in function parameters. You are working with the same reference... Tricky !
Great article! Thanks.
Thanks for interesting article.
Excellent website. Good work. Very useful. I will bookmark!
Post a Comment