Class initialization

Jesse Jaggars jhjaggars at gmail.com
Sun Aug 8 11:13:00 EDT 2010


On Sun, Aug 8, 2010 at 10:01 AM, Tim Harig <usernet at ilthio.net> wrote:
> On 2010-08-08, Costin Gament <costin.gament at gmail.com> wrote:
>> Thank you for your answer, but it seems I didn't make myself clear.
>> Take the code:
>> class foo:
>>   a = 0
>>   b = 0
>> c1 = foo()
>> c1.a = 5
>> c2 = foo()
>> print c2.a
>> 5
>>
>> Somehow, when I try to acces the 'a' variable in c2 it has the same
>> value as the 'a' variable in c1. Am I missing something?
>
> Others have told you that at a and b belong to the class object rather then
> to the instance objects.  Perhaps this will demonstrate the difference:
>
>>>> class foo():
> ...     def __init__(self):
> ...             self.a = 0
> ...             self.b = 0
> ...
>>>> c1 = foo()
>>>> c1.a = 5
>>>> c2 = foo()
>>>> print c2.a
> 0
>>>>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Is it possible that you are using a mutable class object? A common
gotcha is to do something like this:

>>> class foo(object):
...   x = []
...
>>> a = foo()
>>> b = foo()
>>> a.x.append(123)
>>> b.x
[123]

And expect b.x to be an empty list.



More information about the Python-list mailing list