Controlling assignation

Xavier Décoret Xavier.Decoret at imag.fr
Mon Jun 13 12:06:45 EDT 2005


Xavier Décoret a écrit :
> I would like to know if there is for python's classes an equivalent of 
> the operator= that can be overidden.
> 
> Let's say I have
>  >>> a=A()
> and I want to write
>  >>> a=5
> and I want this to change some internal value of a instead of making a 
> point to a new object (an int 5)
> 
> In other word, I would like to be able to use a=5 instead of a.set(5)
> 
> Is that possible?

Thanks anybody for the answers. It confirms what I understood of Python.
What I wanted to do is something like this:

def change(x,v):
	x = v

class A(object):
	def __init__(self,v):
		self.x = v

a = A(3)
print a.x  # displays 3
change(a.x,4)
print a.x  # still displays 3


It may seem weird, but I ensure there is a reason for doing this. In C++ 
(the language I am mot familiar with), I could define f to take a 
pointer to member function of a class, a pointer and a value and achieve 
what I want. In python, I cannot that way becauswe when change(a.x,4) is 
executed, a.x is "replaced" by ist value (returned by __getattribute__).

Finally, here is how I hold the situation:


class Handle:
     def __init__(self,v):
         self.__v = v
     def __call__(self):
         x = self.__v
         while callable(x): x=x()
         return x
     def set(self,v):
         self.__v = v

class HandledProperty(object):
     def __init__(self,name=""):
         self.name = name
     def __get__(self,o,t):
         return o.__dict__[self]
     def __set__(self,o,v):
         o.__dict__[self] = Handle(v)

class A(object):
	x = HandledProperty("x")
	def __init__(self,v):
		self.x = v

def change(x,v):
	x.set(v)


a = A(3)
print a.x()  # displays 3 (notice the () in the call)
change(a.x,4)
print a.x()  # still displays 4



More information about the Python-list mailing list