Koldar
Koldar

Reputation: 1407

attaching __call__ at runtime not working

I'm trying to define the __call__ dunder method at runtime, but with no success. The code is the following:

class Struct:
    pass

result=Struct()
dictionary={'a':5,'b':7}
for k,v in dictionary.items():
    setattr(result,k,v)

result.__call__=lambda self: 2

However, the interpreter returns the error:

Traceback (most recent call last):
 File "<input>", line 1, in <module>
TypeError: 'Struct' object is not callable

But, if I add the dunder method since the beginning, all magically works:

class Foo():
   def __call__(self):
      return 42

foo=Foo()
foo() #returns 42

I'm using Python 3.4 on windows 64bit machine.

Where am I doing wrong?

Upvotes: 2

Views: 72

Answers (1)

kwarunek
kwarunek

Reputation: 12577

Edited

You can attach __call__ by adding it to the class object:

Struct.__call__ = lambda self: 2

But if you want to get different values per instance you should:

class Struct:
    def __call__(self):
        return self._call_ret

result=Struct()
dictionary={'a':5,'b':7}
for k,v in dictionary.items():
    setattr(result,k,v)
    result._call_ret = 2

print(result())

@Blckknght thanks.

Upvotes: 3

Related Questions