Controlling assignation
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Jun 13 16:57:41 EDT 2005
Xavier Décoret a écrit :
(snip)
> 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,
It does
> but I ensure there is a reason for doing this.
I really wonder what it can be ???
> 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
You could achieve the same effect with:
class A( object):
def __init__(self, value):
self.value = value
a = A(3)
a.value = 4
a.value
=> 4
And it's *much* more simple/readable/efficient.
Ever googled for "evolution of a programmer" ?-)
More information about the Python-list
mailing list