bayesian
bayesian

Reputation: 75

Python classes: linked attributes

Is there a more pythonic way of 'linking' attributes such that when one attribute in a class is changed, another can be automatically changed according to some relation that I define?

Currently, I'm doing something like:

class myClass(object):
    def __init__(self):
        self.x = 1
        self.y = 2 * self.x
        pass
    def set_x(self, x):
        self.x = x
        self.y = 2 * self.x
        return
A = myClass()
print A.x #prints 1
print A.y #prints 2
A.set_x(5)
print A.x #prints 5
print A.y #automatically changes to 10

Upvotes: 1

Views: 1611

Answers (2)

JBernardo
JBernardo

Reputation: 33407

You can use properties:

class myClass(object):
    def __init__(self):
        self.x = 1

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        self._x = x
        self.y = 2 * self._x

And a test:

>>> c= myClass()
>>> c.x = 10
>>> c.x
10
>>> c.y
20

Upvotes: 4

Michael
Michael

Reputation: 2281

You could use getters and setters:

class myClass(object):
    def __init__(self):
        self.x = 1

    @property
    def y(self):
        return 2 * self.x
    ...

Basically, this is saying is when you try to get A.y, it returns self.x * 2 instead.

And considering the rest of the class, I would actually do something like this:

class myClass(object):
    def __init__(self):
        self._x = 1

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return 2 * self._x

    @x.setter
    def x(self, val):
        self._x = val

Upvotes: 3

Related Questions