简体   繁体   English

使用外部函数更新内部python类参数

[英]Updating internal python class parameters with external functions

I have an external function my_update_function which is not part of my class my_class (currently for design reasons). 我有一个外部函数my_update_function ,它不是我的类my_class一部分(当前出于设计原因)。 Now, I would like to update the internal parameters of my_class ie self.x and self.y using the external function my_update_function . 现在,我想使用外部函数my_update_function更新my_class的内部参数,即self.xself.y

Please see this MWE, which describes my questions: 请参阅此MWE,其中描述了我的问题:

def my_update_function(arg1,args2):
    """
    Updates arg1 and arg2.
    """
    return arg1*arg1,arg2*arg2

class my_class(object):
    def __init__(self):
        self.x = 2
        self.y = 3
    def simulate(self):
        my_update_function(self.x,self.y)

However, I am wondering if there is some way (either by class re-design or otherwise) that I can update self.x and self.y without having to save the output of the function my_update_function as parameter values (and without having to include my_update_function as part of my class my_class ) ie I would rather not write this: 然而,我想知道是否有一些方法(或者通过类重新设计或以其它方式),我可以更新self.xself.y而无需保存该函数的输出my_update_function作为参数值(并且不必包括my_update_function作为我的类my_class一部分),即我不愿意这样写:

def simulate(self):
    self.x, self.y = my_update_function(self.x,self.y)

but would want it to be like this: 但希望它像这样:

def simulate(self):
    my_update_function(self.x,self.y)

so that my_update_function communicates the updated parameter values to the class without having to explicitly store them as outputs. 这样my_update_function可以将更新后的参数值传达给该类,而不必显式地将它们存储为输出。

Please let me know if it is not clear what I mean, and I shall update the question. 如果不清楚我的意思,请告诉我,我将更新问题。

def my_update_function(obj):
    obj.x, obj.y = obj.x * obj.x, obj.y * obj.y

then in your class: 然后在你的课上:

class my_class(object):
    def __init__(self):
        self.x = 2
        self.y = 3
    def simulate(self):
        my_update_function(self)

Since python does not have pointers, a common trick is to use lists, which are passed by reference, and hence their contents is mutable : 由于python没有指针,因此一个常见的技巧是使用列表,这些列表是通过引用传递的,因此它们的内容是可变的

>>> def my_update_function(l):
...     l[0], l[1] = l[0] * l[0], l[1] * l[1]
...
>>> l = [2, 3]
>>> my_update_function(l)
>>> l
[4, 9]

I'm adding this as a second answer to not create confusion. 我将此添加为第二个答案,以免造成混乱。

Using an object instead of a list works the same way (both are passed by reference), and you already have an object at hand, so you better off using the my_class object. 使用对象而不是列表的工作方式相同(两者均通过引用传递),并且手头已有对象,因此最好使用my_class对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM