overloading operators for a function object

  • Thread starter Fletcher Johnson
  • Start date
F

Fletcher Johnson

Is it possible to overload operators for a function?

For instance I would like to do something roughly like...

def func_maker():
def func(): pass

def __eq__(other):
if other == "check": return True
return False

func.__eq__ = __eq__
return func

newfunc = func_maker()
newfunc == "check" #true
newfunc == "no" #false
 
C

Chris Rebert

Is it possible to overload operators for a function?

For instance I would like to do something roughly like...

def func_maker():
 def func(): pass

 def __eq__(other):
   if other == "check":  return True
   return False

 func.__eq__ = __eq__
 return func

newfunc = func_maker()
newfunc == "check" #true
newfunc == "no" #false

You can write a callable [wrapper] object to get the same effect:

class SpecialFunction(object):
def __call__(self, actual, args, go, here):
return whatever

def __eq__(self, other):
return other == "check"

newfunc = SpecialFunction()
newfunc == "check" # => True
newfunc(1, 2, 3, 4) #=> whatever

Cheers,
Chris
 
W

Westley Martínez

Is it possible to overload operators for a function?

For instance I would like to do something roughly like...

def func_maker():
def func(): pass

def __eq__(other):
if other == "check": return True
return False

func.__eq__ = __eq__
return func

newfunc = func_maker()
newfunc == "check" #true
newfunc == "no" #false

I'm curious as to what you're going to use this for.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top