简体   繁体   English

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

[英]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 : 然后添加speedweight

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 up d in the dictionary of obj . 例如, obj.dobj的字典中查找d If d defines the method __get__() , then d.__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.

相关问题 python:通过变量调用类实例 - python: call class instance by variable 如何调用存储在Python类实例变量中的函数 - How to call a function stored in a Python class instance variable Python:在函数外调用类实例 - Python: call class instance outside function 使用函数变量调用类实例时,Python的“ str”对象没有属性“名称” - Python 'str' object has no attribute 'name' when using a function variable to call a class instance 从python中的函数调用类实例的类属性 - Call a class attribute of a class instance from a function in python 为什么 python property() function 被分配给 class 变量而不是实例变量? - Why python property() function is assigned to a class variable and not an instance variable? Python:动态使用变量调用类实例中的字典键 - Python: Using a variable dynamically to call a Dictionary Key in a Class instance 模拟一个在方法调用后更改实例变量的python类? - Mocking a python class which changes an instance variable after a method call? Python标准(PEP)名称到函数调用中的未知类实例 - Python standard (PEP) name to unknown class instance in function call Python:通过字符串调用将类实例传递给函数 - Python: Passing a class instance to a function via a string call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM