[英]How to pass function to class with specific arguments?
我喜歡將一個有 2 個參數的函數傳遞給一個類,其中 1 個參數是“預定義的”。 當我從類實例中調用函數時,我只想給出第二個變量(因為我已經定義了第一個)。 例子:
def my_fun(a, b):
return a+b
class MyClass():
def __init__(self, fun):
self._fun = fun
def class_function(self, c):
return self._fun(c)
instance = MyClass(my_fun(a=5.0))
print(instance.class_function(10.0))
這可能嗎?
使用functools
模塊中的partial
。
from functools import partial
def my_fun(a, b):
return a + b
class MyClass():
def __init__(self, fun):
self._fun = fun
def class_function(self, c):
return self._fun(c)
instance = MyClass(partial(my_fun, 5.0))
print(instance.class_function(10.0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.