Python 类实例变量的自动函数调用?

Mat*_*hew 1 python variables class function instance

所以可以说我有一个Car如下所示的类:

class Car(object):
    """Car example with weight and speed."""
    def __init__(self):
        self.weight = None
        self.speed = None
Run Code Online (Sandbox Code Playgroud)

如果我将 a 初始化Car为空对象:

red_car = Car()
Run Code Online (Sandbox Code Playgroud)

我添加了一个speed和一个weight

red_car.speed = 60
red_car.weight = 3500
Run Code Online (Sandbox Code Playgroud)

一切都很好,但是如果我想在尝试将这些变量添加到实例时运行一个函数怎么办?像这个功能:

def change_weight(self, any_int):
    return (any_int - 10)
Run Code Online (Sandbox Code Playgroud)

问题是,当我尝试向对象添加特定实例变量时,我希望它自动运行此函数。如果可能,我希望它change_weight仅在weight实例变量上运行。

我是否正确理解这一点,还是应该单独通过函数运行整数,然后手动添加到对象中?

Ant*_*ala 7

你想使用属性

class Car(object):
    """Car example with weight and speed."""
    def __init__(self):
        self._weight = None # internal value
        self.speed = None

    @property
    def weight(self):
        return self._weight

    @weight.setter
    def weight(self, the_weight):
        self._weight = the_weight - 10 # or whatever here
Run Code Online (Sandbox Code Playgroud)

现在,您可以speed正常设置了;当您执行car.weight = 20setter 函数时,将调用该函数,并将实际重量设置为20 - 10 = 10