2 Replies - 768 Views - Last Post: 01 September 2011 - 01:15 PM Rate Topic: -----

#1 cupidvogel   User is offline

  • D.I.C Addict

Reputation: 31
  • View blog
  • Posts: 593
  • Joined: 25-November 10

Function working without arguments?

Posted 01 September 2011 - 10:28 AM

Hi, can please anyone explain how does this code work, even though the function isn't fed any argument?

def func( ):
x = 4
action = (lambda n: x ** n) # x remembered from enclosing def
return action
x = func( )
print x(2) # Prints 16, 4 ** 2



Firstly, I know functions can be assigned to other variables like object reference, i.e. f = func. But here it is assigned like x = func(). Why and what does it mean? Secondly, I call x(2) alright, but there is no parameter in the function definition of func (and thus x) to accept it, so how come the variable n inside the lambda get its value?

This post has been edited by cupidvogel: 01 September 2011 - 10:33 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Function working without arguments?

#2 Motoma   User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 798
  • Joined: 08-June 10

Re: Function working without arguments?

Posted 01 September 2011 - 10:57 AM

You've created a function to create a lambda function. A simple description of a lambda function is an inline function that acts with the scope in which it is called. You could compare this to writing the contents of the lambda everywhere the lambda is used.
Was This Post Helpful? 0
  • +
  • -

#3 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7506
  • View blog
  • Posts: 15,556
  • Joined: 16-October 07

Re: Function working without arguments?

Posted 01 September 2011 - 01:15 PM

If it makes more sense:
>>> def func():
...     def returnFunc(n):
...             x = 4
...             return x ** n
...     return returnFunc
... 
>>> 
>>> x = func( )
>>> 
>>> print x(2)
16
>>> 



A function is an object. You're just passing an object.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1