![](/img/trans.png)
[英]Python - method of a class with an optional argument and default value a class member
[英]Python -Passing a class method as the default value of an argument to another class initialization
修改原始問題以防止混淆。 我在 2 個不同的模塊中定義了 2 個類:
class Heuristic:
def process(self,data,x,y):
processed_data = (data + x) /y
return processed_data
class GTS(Abstract_Strat):
def __init__(self, data, method= Heuristic().process(),*args):
self.data= data
self.method = method
self.func_args = args
所以在類 GTS 中,在初始化函數中,我試圖傳遞一個屬於另一個模塊中的類啟發式的方法。 嘗試此操作時,出現以下錯誤:
TypeError: process() takes exactly 3 arguments (1 given)
我搜索計算器,發現在類似的問題Typerror
提到的_init_
方法。 但在這種情況下,錯誤是針對作為參數傳入_init_
方法的函數。 所以問題是 - 將一個類的方法作為默認參數值傳遞給另一個類的初始化器的正確方法是什么?
在python中,您必須先構造類的實例,然后才能訪問對象,然后訪問它的方法。
您可能會執行以下操作:
class GTS(Abstract_Strat):
heuristic = Heuristic(data)
def __init__(self, data, method= heuristic.process(),*args):
self.data= data
self.method = method
self.func_args = args
從而構建您的對象並讓您訪問其“綁定”方法。 它所指的第一個參數是定義中的“self”,在初始化類的實例之前您無權訪問它。
我分辨通過改變改性問題中提到上述問題Heuristic().process()
到Heuristic().process
傳遞,當它作為函數參數的默認值。
還要感謝安德魯對問題原始版本的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.