[Tutor] Variable Modification in a class
Mehta, Anish
Anish.Mehta@enst-bretagne.fr
Tue Jun 3 11:18:17 2003
But if i quote it from the same example in C here:
typedef struct ab
{
int a;
int b;
}AB;
main()
{
AB b;
AB c;
b.a = 5;
b.b = 10;
c = b;
c.a = 30;
c.b = 40;
printf("AB values %d %d\n", b.a, b.b);
printf("New values %d %d\n", c.a, c.b);
}
The output is:
AB values 5 10
New values 30 40
Where does the difference lie between this code and its equivalent
python code. Where i am going wrong in my python code for this type of
code in C
Waiting for reply
Thanks for responding
Regards
Tom Jenkins wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Mehta, Anish wrote:
> | Hello!
> |
> | I am having a problem in tackling the variables in the class.
> |
> | class ab:
> | def __init__(self):
> | self.a = None
> | self.b = None
> |
> | def func(ab):
> | b = ab
> | c = ab
> |
> | b.a = 5
> | b.b = 10
> |
> | c = b
> | c.a = 30
> | c.b = 40
> |
> | print b.a, b.b
> | print c.a, c.b
> | t = func(ab())
> |
> |
> | Output is
> | 30 40
> | 30 40
> |
> | I want the output to be
> | 5 10
> | 30 40
> |
> | I mean every instance should modify its own set of variables not the
> | variables of the other instances of the class. The output of the set of
> | variables of b should not be affected by modifying those variables by
> | another instance of the same class.
> |
>
> That is completely correct. However you are not modifying different
> instances of the class, you are modifying the same instances...
>
> | def func(ab):
> | b = ab
> | c = ab
>
> b and c both reference instance ab;
>
> | b.a = 5
> | b.b = 10
> |
>
> make changes to instance referenced by b (and since b and c reference
> same instance, c as well)
>
> | c = b
>
> even if above you hadn't explicitly made b and c reference the same
> instance, here you are again saying c should reference the same instance
> as b
>
> | c.a = 30
> | c.b = 40
>
>
> make changes to instance referenced by c (and since b and c reference
> same instance, b as well)
>
> what i _think_ you want is...
>
> def func(ab):
> ~ b = ab()
> ~ c = ab()
>
> ~ b.a = 5
> ~ b.b = 10
>
> ~ c.a = 30
> ~ c.b = 40
>
> ~ print b.a, b.b
> ~ print c.a, c.b
> t = func(ab)
>
> - --
> Tom Jenkins
> devIS - Development Infostructure
> http://www.devis.com
>
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.2.0-nr2 (Windows XP)
> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
>
> iD8DBQE+3LREV7Yk9/McDYURAlFJAKCdAVAy5GFTfmSUeG1m7DJ/X0S3uQCggGO5
> IpjU6AYJNKnNFc7LePiLrfU=
> =kQHH
> -----END PGP SIGNATURE-----
>
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>