Looking for assignement operator

Laurent Pointal laurent.pointal at limsi.fr
Tue Oct 17 10:15:39 EDT 2006


Alexander Eisenhuth a écrit :
> Hello,
> 
> is there a assignement operator, that i can overwrite?

Adding to Simon Brunning reply (assignment is a statement).

> class MyInt:
>     def __init__(self, val):
>         assert(isinstance(val, int))
>         self._val = val
> 
> a = MyInt(10)
> 
> # Here i need to overwrite the assignement operator
> a = 12

Here you bind the 12 (Python int value) to name 'a', then 'a' has the
int type, not your MyInt (which value has been lost).

You may define a 'set' method, and write:
a = MyInt(10)
a.set(12)

And, if a is a member of another class, you may define an accessor for
that 'a' member in that class, which automatically call your set method
when giving an int value.

b.a = MyInt(10)
b.a = 12		---> b.a.set(12)

A+

Laurent.



More information about the Python-list mailing list