自动函数调用Python类的实例变量? [英] Automatic function call on instance variable of Python class?
问题描述
<$ c $ c> class Car(object):
汽车以重量和速度为例。
def __init __(self):
self.weight = None
self。速度=无
如果我初始化一个 Car
作为空对象:
red_car = Car()
我添加了一个速度
和一个权重
: p>
red_car.speed = 60
red_car.weight = 3500
这很好,但如果我想在试图将这些变量添加到实例时运行一个函数呢?像这个函数:
def change_weight(self,any_int):
return(any_int - 10)
虽然我希望它在我尝试将特定实例变量添加到对象时自动运行此函数。如果可能,我希望它只在权重
实例变量上运行 change_weight
。
我是否正确理解这个问题,或者我应该单独通过函数运行整数,然后手动添加到对象中?
你想使用属性
class Car(object):
def __init __(self):
self._weight = None#内部值
self.speed =无
@财产
def weight(self):
return self._weight
@ weight.setter
def weight(self,the_weight):
self._weight = the_weight - 10#or any here
现在,您可以设置 speed
通常;当你执行 car.weight = 20
时,setter函数将被调用,实际重量将被设置为 20 - 10 = 10
。
So lets say I have a class called Car
as below:
class Car(object):
"""Car example with weight and speed."""
def __init__(self):
self.weight = None
self.speed = None
If I initialize a Car
as an empty object:
red_car = Car()
And I add a speed
and a weight
:
red_car.speed = 60
red_car.weight = 3500
That's all fine but what if I want to run a function when attempting to add those variables to the instance? Like this function:
def change_weight(self, any_int):
return (any_int - 10)
The thing is though I want it to automatically run this function whenever I attempt to add specific instance variables to the object. If possible I would like it to run change_weight
only on the weight
instance variable.
Am I understanding this correctly or should I just be running the integer through the function separately and then adding to the object after manually?
You want to use properties
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
Now, you can set speed
normally; when you execute car.weight = 20
the setter function will be called, and the actual weight will be set to 20 - 10 = 10
.
这篇关于自动函数调用Python类的实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!