Dear Nick, dear Andreas, Imagine you add two ints i1 and i2, one in and one outside of __init__, none of them gets shared to other instances of test. They are always initialized to what the class definition says to. Please refer the modified example. In your sense, Andreas, c2 should also see a modified version of i1. And in yours, Nick, i1 should be a unique int shared by all instances of test. That's not true actually. In my opinion, initialization outside of __init__ without self. and inside __init__ with self. should work absolutely identical. Best regards Oliver Oliver Walczak wrote:
So, is it a bug or a feature? In my eyes this behaviour is not what the programmer has got to expect. Who knows whats happening there and can explain me if it makes any sense?
Dear List,
recently i got stuck on a strange class initialization bug. Please refer
The output is exactly what I expected:
c1, before:
d1= {'key': 'value'}
d2= {'key': 'value'}
c1, after:
d1= {'key': 'value2'}
d2= {'key': 'value2'}
c2:
d1= {'key': 'value2'}
d2= {'key': 'value'}
Exactly what do you believe is mysterious here? c2 sees the modified version
of
the class variable (d1), and sees a fresh copy of the instance variable
(d2).
Please make you question more explicit.
Regards,
Nick.
"Oliver Walczak"
sample attached for a demonstration and watch what happens to d2 in the second class instance. This only works on dictionaries. Any other types initialized outside of __init__ seem to work perfectly.
Did you try with type list? You modify the object referenced by d1, and that object is created when the class is defined. All instances of test share the dictionary referenced by d2, and have a unique dictionary referenced by d1. That what your class definition says, so I'd say it's a feature not a bug.
So, is it a bug or a feature? In my eyes this behaviour is not what the programmer has got to expect. Who knows whats happening there and can explain me if it makes any sense?
Best regards Oliver
#!/usr/bin/python # -*- coding: iso-8859-1 -*-
class test: d1 = {'key':'value'} def __init__(self): self.d2 = {'key':'value'}
def Show(self): print 'd1=',self.d1 print 'd2=',self.d2
c1 = test() print 'c1, before:' c1.Show() c1.d1['key'] = 'value2' c1.d2['key'] = 'value2' print 'c1, after:' c1.Show()
c2 = test() print 'c2:' c2.Show()
Short answer for py-dev: This is not a bug. It is how the language works. I'll give some further explanation in private mail - any additional queries should go to comp.lang.python. Cheers, Nick. -- Nick Coghlan | Brisbane, Australia Email: ncoghlan@email.com | Mobile: +61 409 573 268
participants (2)
-
Nick Coghlan
-
Oliver Walczak