Flash
Flash

Reputation: 75

What is the logic behind closure property in OOPs?

I have a doubt regarding the concept of closure in an object-oriented programming language. so by definition, closure is a concept of an inner function having access to free variables(variables which are created in the outer function).

I want to know, why an inner function has this property? what is the logic behind this functionality of an object-oriented programming language?

P.S. I am learning OOPs in Python... If anybody has any idea please help :) Thank you

Upvotes: -2

Views: 220

Answers (2)

SimonR
SimonR

Reputation: 1824

This allows you to write functions which behave as "function-factories". So you call the outer function with some argument, which returns the inner function (note, crucially, it doesn't call the inner function).

e.g.

def times_n(n):
    def func(x):
        return x*n
    return func 

This returns a function which will then accept arguments, and multiply them by the 'n' you passed to the outer function:

E.g.

times_three = times_n(3)

times_three(4)

=> returns 12

All this is possible because functions in python are first-class objects: you can pass them around, assign them to variables, and in this case, return them from a function.

Upvotes: 2

Ori Cohen
Ori Cohen

Reputation: 185

The short answer is that closure has no place in object oriented programming. You see it a lot in python because while the language does support the concept of objects, it is not in and of itself an object oriented language. It is truer to say that python supports many programming paradigms, and the the idea of closure comes from the functional side of the language. If you're interested, you can read more here (the examples are in JS, but the idea is the same): “Functional programming paradigms in modern JavaScript: Partial Application” by Alexander Kondov https://link.medium.com/F492cDEhz6

Upvotes: 0

Related Questions