[英]Automatic function call on instance variable of Python class?
So lets say I have a class called Car
as below: 所以可以说我有一个叫做
Car
的类,如下所示:
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: 如果我将
Car
初始化为空对象:
red_car = Car()
And I add a speed
and a weight
: 然后添加
speed
和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. 如果可能的话,我希望它仅对
weight
实例变量运行change_weight
。
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; 现在,您可以正常设置
speed
。 when you execute car.weight = 20
the setter function will be called, and the actual weight will be set to 20 - 10 = 10
. 当您执行
car.weight = 20
,将调用setter函数,实际重量将设置为car.weight = 20
20 - 10 = 10
。
Read up on Python's notion of Descriptors . 阅读有关Python的描述符的概念。 In particular, it sounds like you want to define a custom
__set__()
method. 特别是,听起来您想定义一个自定义
__set__()
方法。
For example,
obj.d
looks upd
in the dictionary ofobj
.例如,
obj.d
在obj
的字典中查找d
。 Ifd
defines the method__get__()
, thend.__get__(obj)
is invoked according to the precedence rules listed below.如果
d
定义了方法__get__()
,则根据下面列出的优先级规则调用d.__get__(obj)
。
Alternately, you may find using Properties
(a specific type of Descriptor) a little easier to work with. 另外,您可能会发现使用
Properties
(一种特定类型的描述符)更容易使用。
property()
is a succinct way of building a data descriptor that triggers function calls upon access to an attribute.property()
是构建数据描述符的简洁方法,该描述符在访问属性时触发函数调用。
The behavior of descriptors is fairly logical once you understand it, but it doesn't behave quite as you might expect; 一旦理解了描述符的行为,这是很合乎逻辑的,但是它的行为并不像您期望的那样。 in particular,
__get__()
and __set__()
should not be confused with getters and setters, like the Java concept. 特别是,
__get__()
和__set__()
与getter和setter混淆,例如Java概念。 So look at some of the examples above and play around with them before diving in. 因此,请看上面的一些示例,并在深入研究之前与它们一起玩。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.