簡體   English   中英

使用外部函數更新內部python類參數

[英]Updating internal python class parameters with external functions

我有一個外部函數my_update_function ,它不是我的類my_class一部分(當前出於設計原因)。 現在,我想使用外部函數my_update_function更新my_class的內部參數,即self.xself.y

請參閱此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)

然而,我想知道是否有一些方法(或者通過類重新設計或以其它方式),我可以更新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)

但希望它像這樣:

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

這樣my_update_function可以將更新后的參數值傳達給該類,而不必顯式地將它們存儲為輸出。

如果不清楚我的意思,請告訴我,我將更新問題。

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

然后在你的課上:

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

由於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]

我將此添加為第二個答案,以免造成混亂。

使用對象而不是列表的工作方式相同(兩者均通過引用傳遞),並且手頭已有對象,因此最好使用my_class對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM