0

This answer shows how to pass functions with arguments to another function. On the other hand, this answer shows how to call a class method from an instance. Both the examples work great. However, in my case, if I pass an outside function as class method and call it from instance it 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)

The above code is throwing the following error:

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'

Clearly, there are two values 10, and 20 that being passed to myfun() via obmeth(), then what is causing this error?

UPDATE

The error was due to the following typo

self.bar(args) should be self.bar(*args) as pointed out by @Barmar

aroyc
  • 890
  • 2
  • 13
  • 26

1 Answers1

0

As @Barmar pointed out I should have unpack the arguments. Therefore, replacing print(self.bar(args)) with print(self.bar(*args)) solves the problem.

aroyc
  • 890
  • 2
  • 13
  • 26