Are a class's methods a type of closure?
No. A closure is a very specific type of function. As Wikipedia says, they implement lexical scoping.
Closures
In Python, such a closure would look like this:
def startAt(x):
def incrementBy(y):
return x + y
return incrementBy
The variable x
is bound (in Python's case, immutably) in the incrementBy
that is created when startAt
is called. (x
could very well be a mutable data structure, or the implementation of your language may allow you to change it.)
For contrast, here is a non-closure function example that uses a global:
x = 0
def incrementBy(y):
return x + y
Here, there is a single function, incrementBy
, and whenever x changes on the global scope, it is reflected in the function:
>>> incrementBy(5)
5
>>> x = 1
>>> incrementBy(5)
6
Methods
Methods, on the other hand, have access to mutable variables. If they are instance methods, they know their instance, and thus class. If they are class-methods, they know their class. Even if they are static methods, not knowing class or instance, they still may use globals. The globals may be reassigned at will, and can thus change the outputs of the function for any given.
You can make a closure into a method appended to a class, depending on the implementation of your language:
class Foo(object):
ib5 = staticmethod(startAt(5))
>>> Foo.ib5(3)
8
>>> Foo.ib5
<function incrementBy at 0x7f29e978b758>
But I don't think that's what you actually mean to do.
What is a closure?
A closure is an inner function that binds variables to it from the outer function's scope. If a class's method doesn't do this, it's not a closure.
Comparing and Contrasting Methods and Closures
What they have in common, is combining functionality with data.
Where they contrast is closures bind data to functionality, whereas methods bind functionality to data structures. So it would not be correct to call a method a type of closure unless it really is a closure.
I would assert that most class's methods don't do this, but I'll allow that there may be environments where this is a recognized technique. I'd be very interested to know who is using this and what their justification is.
I have personally never seen this being done in the wild.
this
) or a class. Unlike closures, methods do not capture the outer environment, though.