【问题标题】:Passing functions with arguments to another function, and then calling via method is throwing error将带参数的函数传递给另一个函数,然后通过方法调用会引发错误
【发布时间】:2022-06-17 02:25:01
【问题描述】:

This 答案显示了如何将带参数的函数传递给另一个函数。另一方面,this answer 展示了如何从实例调用类方法。这两个例子都很好用。但是,就我而言,如果我将外部函数作为类方法传递并从实例调用它,则会引发错误。

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(),那么是什么导致了这个错误?

更新

错误是由于以下拼写错误

@Barmar 指出,self.bar(args) 应该是 self.bar(*args)

【问题讨论】:

  • 你忘了传播论点:self.bar(*args)
  • 非常感谢@Barmar!

标签: python function arguments static-methods


【解决方案1】:

正如@Barmar 指出的那样,我应该解压缩参数。因此,将print(self.bar(args)) 替换为print(self.bar(*args)) 即可解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 2014-05-05
    相关资源
    最近更新 更多