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.

asked Jan 29, 2013 at 19:00
2
  • Could I ask what the use case is then? Commented Jan 29, 2013 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 Commented Jan 29, 2013 at 19:46

1 Answer 1

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)
answered Jan 29, 2013 at 19:03
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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 :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.