开发者

Transitive value assignation in Python classes

I don't think it can be done easily, but here is the thing:

Assume you have a simple class like this:

class Demo:
    a = 'to update'
    b = a

As you can see, I w开发者_如何学JAVAant the variable 'b' to be another name for variable 'a'. So, what I want to do is something like this:

>>> demo = Demo()
>>> demo.a
'to update'
>>> demo.b
'to update'
>>> demo.b = 'updated'
>>> demo.b
'updated'
>>> demo.a
'updated'

So, this is an example of what I want to achieve. What I want to do is to set a value to variable 'a' when I set a value for variable 'b'. My first guess is to set both variable to have a reference to the actual value, so they're pointing to the same element.

Any guess? Previous thanks to any one answering!

PD: The value must be a string.


You can't hook into assignment to get the effect you're looking for. You're right that you'll need to set both a and b to the same mutable object, and change your assignment to be something that mutates the object.

class Demo:
    a = ['to update']
    b = a

>>> demo = Demo()
>>> demo.a[0]
'to update'
>>> demo.b[0]
'to update'
>>> demo.b[0] = 'updated'
>>> demo.b[0]
'updated'
>>> demo.a[0]
'updated'

You could also use properties to achieve the same effect, though a and b would be instance attributes, not class attributes:

class Demo(object):
    def __init__(self):
        self._shared = None

    @property
    def a(self):
        return self._shared

    @a.setter
    def a(self, value):
        self._shared = value

    @property
    def b(self):
        return self._shared

    @b.setter
    def b(self, value):
        self._shared = value


Here is an option.

class Test(object):

    ab = "Original"

    def getval(self):
        return self.ab

    def setval(self, val):
        self.ab = val

    a = property(getval, setval)
    b = property(getval, setval)


t = Test()
print t.a, t.b
t.a = "Hello"
print t.a, t.b

output is,

Original Original
Hello Hello
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜