1

I am trying to make a function that returns itself with parameters.

Def a (x,y):
   *code*
   Return a(x,y)

this returns an error when I try to run it.

>>> a(1,2)
RecursionError: maximum recursion depth exceeded

What I want is

>>> a(1,2)
a(1,2)

It there a way to return the function with parameters?

I know it can be done but I don’t know how to do it

>>> datetime.time(0,0)
Datetime.time(0,0)

Edit: Preferably I would like not to have to import any modules

John
  • 23
  • 5

4 Answers4

1

It looks like you have no valid return. The error means it calls itself so many times python just gives up. Example (good) will end after ''num'' times:

def a(x, num):
  if num == 0:
    return x
  return a(x + 1, num - 1)

Example (bad) will never return anything else as itself:

def a(x, num):
  if num == 0:
    return x
  return a(x + 1, num)
Tom Nijhof
  • 542
  • 4
  • 11
0

Assuming you mean you want it to return a string representation of the function as called:

def a (x,y):
   *code*
   return f"a({x},{y})"

Alternatively if you are not able to use f-strings:

def a (x,y):
   *code*
   return "a({x},{y})".format(x=x, y=y)
PyPingu
  • 1,697
  • 1
  • 8
  • 21
0

I think you've misunderstood what is "returned" when you call the following row:

>>> datetime.time(0,0)
Datetime.time(0,0)

The original call datetime.time(0,0) creates a datatime-object to the console. Because you're not saving the returned object, the console automatically calls for the class-method called __repr__.

To replicate the behavior we can create the following class:

>>> class a:
...   def __init__(self, x,y):
...     self.x = x
...     self.y = y
...   def __repr__(self):
...     return "a({},{})".format(self.x, self.y)
...
>>> a(1,2)
a(1,2)
Hampus Larsson
  • 3,050
  • 2
  • 14
  • 20
0

Maybe using a nested function or lambda ?

$ python -q
>>> def a(x,y):
...     def _a():
...             return x + y
...     return _a
... 
>>> a(1,2)
<function a.<locals>._a at 0x7f048329e560>
>>> a(1,2)()
3
Charles Paulet
  • 191
  • 1
  • 2