How do you change the value of one attribute by changing the value of another? (dependent attributes)

时间秒杀一切 提交于 2019-12-06 09:59:00

Define darkness as a property

class shade:
    def __init__(self, light):
        self.light=light

    @property
    def darkness(self):
        return 100 - self.light

    def __str__(self):
        return (str(self.light) +  ',' + str(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

class shade:
    def __init__(self, light):
        self.light=light

    @property
    def darkness(self):
        return 100 - self.light

    @darkness.setter
    def darkness(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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!