Skip to content Skip to sidebar Skip to footer

How Do You Change The Value Of One Attribute By Changing The Value Of Another? (dependent Attributes)

So I've recently dived into OOP, and so far everything is going smooth. Whilst I have no issues per se, there's an amazing feature which I hope exists, though I cannot find any doc

Solution 1:

Define darkness as a property

classshade:def__init__(self, light):
        self.light = light

    @propertydefdarkness(self):
        return100 - self.light

    def__str__(self):
        return'{},{}'.format(self.light, self.darkness)

Properties outwardly appear as attributes, but internally act as function calls. When you say s.darkness it will call the function you've provided for its property. This allows you to only maintain one variable internally.

If you want to be able to modify it by assigning to darkness, add a setter for the property

classshade:def__init__(self, light):
        self.light = light

    @propertydefdarkness(self):
        return100 - self.light

    @darkness.setter
    defdarkness(self, value):
        self.light = 100 - value

Thereby actually modifying light. If you've never seen properties before, I'd recommend throwing in some print()s to the bodies of the functions so you can see when they are called.

>>>s = shade(70)>>>s.light
70
>>>s.darkness
30
>>>s.light = 10>>>s.darkness
90
>>>s.darkness = 20>>>s.light
80

Post a Comment for "How Do You Change The Value Of One Attribute By Changing The Value Of Another? (dependent Attributes)"