0

Essentially this is what I want to accomplish:

class Move(object):
    def __init__(self, Attr):
        if Attr:
            self.attr = Attr

        if hasattr(self, "attr"):
            __call__ = self.hasTheAttr
        else:
            __call__ = self.hasNoAttr

    def hasNoAttr(self):
        #no args!

    def hasTheAttr(func, arg1, arg2):
        #do things with the args

    __call__ = hasNoAttr

I know that that doesn't work, it just uses hasNoAttr all the time. My first thought was to use a decorator, but I'm not all that familiar with them and I couldn't figure out how to base it from whether or not a class attribute existed or not.

Actual question part: How would I be able to deterministically make a function either x function or y function depending on a condition.

DanielCardin
  • 545
  • 2
  • 8
  • 17
  • Could I ask what the use case is then? – Jon Clements Jan 29 '13 at 19:19
  • this is for movement code, where the parent object may or may not have a collision attribute. In \__call\__, when you have the attribute, two arguments are needed, none are needed if its there's no attribute. I wanted to do it this way rather than having default arguments so that it would error if I forgot to give those arguments to the one's that needed it (whereas you wouldn't get such an error if I was using default arguments – DanielCardin Jan 29 '13 at 19:46

1 Answers1

3

You can't really do this sort of thing with __call__ -- with other (non-magic) methods, you can just monkey-patch them, but with __call__ and other magic methods you need to delegate to the appropriate method within the magic method itself:

class Move(object):
    def __init__(self, Attr):
        if Attr:
            self.attr = Attr

        if hasattr(self, "attr"):
            self._func = self.hasTheAttr
        else:
            self._func = self.hasNoAttr

    def hasNoAttr(self):
        #no args!

    def hasTheAttr(func, arg1, arg2):
        #do things with the args

    def __call__(self,*args):
        return self._func(*args)
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Well - "you need to" is not exactly accurate - as you can "meta" this kind of thing, but this is the most sensible given lack of any further understanding into the intention of why? – Jon Clements Jan 29 '13 at 19:11
  • @JonClements -- I'm not super comfortable with metaclasses yet -- Feel free to post a solution. I'm sure that I could learn a thing or two from it :) – mgilson Jan 29 '13 at 19:13