I can define an object and assign attributes and methods:
class object:
def __init__(self,a,b):
self.a = a
self.b = b
def add(self):
self.sum = self.a + self.b
def subtr(self):
self.fin = self.sum - self.b
def getpar(self):
return self.fin
obj = object(2,3)
obj.add()
obj.subtr()
obj.getpar()
or provide the same functionality by defining a closure:
def closure(a,b):
par = {}
def add():
par.update({'sum':a+b})
def subtr():
par.update({'fin':par['sum']-b})
def getpar():
return par['fin']
return {'add':add,'subtr':subtr,'getpar':getpar}
clos = closure(2,3)
clos['add']()
clos['subtr']()
clos['getpar']()
I think the object syntax would look cleaner to most viewers, but are there instances in which the use of a closure would be semantically preferable?
In Python, closures can be harder to debug and to use than the more usual objects (you have to save the callables somewhere, access them with the goofy notation
clos['add']etc, …). Consider for example the impossibility of accessing thesumif you find something strange in the result… debugging this kind of thing can be really hard;-)The only real compensating advantage is simplicity — but it basically applies only to really simple cases (by the time you have three callables that are internal functions I’d say you’re overboard in that respect).
Maybe the very strong protection (vs objects’ protection “by convention” for class and instance objects), or the possible higher familiarity to Javascript programmers, might justify using closures rather than classes and instances in marginal cases, but in practice I haven’t found myself in cases where such hypothetical advantages seemed to actually apply — so I only use closures in really simple cases;-).