Kelaberetiv

kəˈlabərətɪv/ 
adjective: collaborative

Bringing together the AI community in Singapore – companies, startups, researchers, students, professionals – to collaborate, find research and business opportunities and talent.

Have an account? Login
New user? Register
Forgot password? Reset

AI Singapore uses a 2FA login mechanism to protect your account. Learn more about it here.

Opportunities

  • Have an interesting story to share?
  • Seeking for AI talent for your organization?
  • Seeking research interns for your labs?
  • Seeking an industry partner for your AI projects?
  • Are you a researcher and seeking an industry partner to do a POC or deployment of your IP/research outcomes?

Python Data Science Toolbox (Part 1)  

  RSS

Liyi Ang
(@liyi)
Member
Joined: 7 months ago
Posts: 52
November 21, 2018 9:08 pm  

Do you have any questions relating to Python Data Science Toolbox (Part 1)? Leave them here!


Quote
kevinkan
(@kevinkan)
New Member
Joined: 4 weeks ago
Posts: 1
April 19, 2019 4:27 pm  

In Chapter 2, there is an example: 

def raise_val(n):
    """Return the inner function."""
    def inner(x):
        """Raise x to the power of n."""
        raised = x ** n
        return raised
    return inner

Question:
In the above codes, Why is "return inner" called without having to pass in the parameter to inner function?

 

 

Cheers,
Kevin Kan


ReplyQuote
ringoshin
(@ringoshin)
Active Member
Joined: 5 months ago
Posts: 7
April 20, 2019 2:41 pm  

When you returned (or assigned) a function name without any argument like that in Python, you were returning (or assigning) an address to the said function. You did not call the function to perform its instructions. Best illustrated as follows using the provided example:

square_it = raise_val(2)   # define a new function to create square values
cube_it = raise_val(3)     # define a new function to create cube values
# now you can use square_it and cube_it just like any other functions
print(square_it(3))        # 3**2 = 9
print(square_it(5))        # 5**2 = 25
print(cube_it(3))          # 3**3 = 27
print(cube_it(5))          # 5**3 = 125

Using square_it as an example, by returning the address to the inner function, you are defining dynamically a new function called square_it(x) via raised_val(2). It behaves the same as if you define it directly like this:

def square_it(x):
   raised = x**2
   return raised

Why do we do it? Decorators for one. You can read the following links for more details:

https://www.datacamp.com/community/tutorials/decorators-python

https://stackoverflow.com/questions/1589058/nested-function-in-python

 


ReplyQuote
Share:
Do NOT follow this link or you will be banned from the site!
  
Working

Please Login or Register