3

I want to call class member function through object .The function is mapped in dictionary to a string. I will actually refer the string(key) to call the function(value). It is giving me error that 1 positional argument is required even when I pass the argument. Why do I have to pass the obj name?

When I pass the object instance as 1st parameter, it works.

class A():
 def foo(self , arg):
    print(arg)
 dict = {"foo" :foo}

outside class :

obj = A()
obj.dict["foo"](10)      #not working

#------------------------
obj.dict["foo"](obj,10)         #working
Arkistarvh Kltzuonstev
  • 6,324
  • 6
  • 21
  • 43
Sumedh
  • 97
  • 5
  • 1
    You don't need `dict`, that's exactly what `getattr` is for. `getattr(obj, 'foo')(10)` – DeepSpace Sep 05 '19 at 10:09
  • "Why do I have to pass the obj name?" Because `obj.dict["foo"](10)` calls the underlying unbounded function, so the instance ("`self`") is not automatically passed to `foo` – DeepSpace Sep 05 '19 at 10:11
  • @DeepSpace Could you explain the 2 scenarios as the OP asked? Linked question don't answer what the OP asked directly. I voted to reopen it again. – Arup Rakshit Sep 05 '19 at 10:22
  • This will require an article to explain, but in short see that `self` in function definition `def foo(self,arg)` ? When you call `obj.foo(arg)` it sees the owner instance and adds it as first argument implicitly, in effect it is called as `A.foo(obj,arg)` , but when you call it in a roundabout way like `obj.dict["foo"](arg) it doesn't see the owner instance of class so it gets called as `A.foo(arg)` again, but by definition foo expects 2 arguments, therefore it fails. Google "static class methods in python" to know more. – IcedLance Sep 05 '19 at 10:23
  • FWIW a "workaround" would be do define `self.dict = {"foo": self.foo}` in `A.__init__` then `obj.dict["foo"](10) ` will work, but again this behavior is already available through the built-in `getattr` – DeepSpace Sep 05 '19 at 10:25
  • @DeepSpace you are always giving another answer to solve it, but not explaining what happened with the current code.. The OP asked he/she don't understand how the current piece of code works. – Arup Rakshit Sep 05 '19 at 10:28
  • @DeepSpace i want to map functions with a string which will be passed to me from another module,thats why i need a dict so as to have a key: value pair. And why the function is unbounded it is defined in class ? – Sumedh Sep 05 '19 at 11:29

0 Answers0