0

I have an instance A a which is called repeatedly like A(i). Since this call is the bottleneck I want to code A.__call__() as perfomant as possible. Gains could be made if I can leverage the information which is available during instance creation, and select the call method based on this information, as in this mock example:

class xxx():
    def __init__(self, **kwargs):
        if kwargs["foo"] == "bar":
           self.__call__ = self.do_B
        else:
           self.__call__ = self.do_C

    def do_A(self):
        return 2
    def do_B(self):
        return 3

A = xxx(foo="bar")

A()

I am aware that there are plenty of posts on how to achieve this after the instance has been created, and that I could simply call A._do_B(i) in my code, but this would clutter the code with plenty of ifs and the above seems to be more natural (to me anyway :-)

Uliw
  • 71
  • 5
  • 1
    Doesn't the example you provided work already? – xjcl Dec 15 '20 at 14:43
  • It isn't obvious to me what the question is? Yes, something similar to this should work. – DavidW Dec 15 '20 at 14:43
  • 1
    Magic methods are generally only looked for in the class, not in the instance. One possibility: give your class a `__new__()` method, that instantiates one of two subclasses based on `kwargs["foo"]`, each of which contains a custom version of `.__call__()`. – jasonharper Dec 15 '20 at 14:46
  • I've edited the above code to be functional. If you run it will throw and error stating that A is not callable. I'll try @jasonharper approach – Uliw Dec 15 '20 at 15:19
  • 2
    Since you've mentioned the error about "is not callable" I've found a question that had essentially the same problem - with some great answers and explanations. I hope the answers in the duplicate help you find a solution for your case. – MSeifert Dec 15 '20 at 15:24

0 Answers0