[英]Passing functions with arguments to another function, and then calling via method is throwing error
這個答案顯示了如何將帶有參數的函數傳遞給另一個函數。 另一方面,此答案顯示了如何從實例調用類方法。 這兩個例子都很好用。 但是,就我而言,如果我將外部函數作為類方法傳遞並從實例調用它,則會引發錯誤。
class Abc:
@classmethod
def setbar(cls, foo):
cls.bar = staticmethod(foo)
def __init__(self):
print('Object created')
def obmeth(self, *args):
print(self.bar(args))
def myfun(a, b):
return a + b
Abc.setbar(myfun)
ob = Abc()
ob.obmeth(10, 20)
上面的代碼拋出以下錯誤:
Object created
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-9a580c2c4d21> in <module>
15 Abc.setbar(myfun)
16 ob = Abc()
---> 17 ob.obmeth(10, 20)
<ipython-input-8-9a580c2c4d21> in obmeth(self, *args)
8
9 def obmeth(self, *args):
---> 10 print(self.bar(args))
11
12 def myfun(a, b):
TypeError: myfun() missing 1 required positional argument: 'b'
顯然,有兩個值 10 和 20 通過 obmeth() 傳遞給 myfun(),那么是什么導致了這個錯誤呢?
更新
錯誤是由於以下錯字
self.bar(args)
應該是self.bar(*args)
正如@Barmar 所指出的那樣
正如@Barmar 指出的那樣,我應該解開論點。 因此,將print(self.bar(args))
替換為print(self.bar(*args))
解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.