The Cache: Technology Expert's Forum
 
*
Welcome, Guest. Please login or register. September 18, 2019, 12:48:41 AM

Login with username, password and session length


Pages: [1]
  Print  
Author Topic: Closures in Python  (Read 2326 times)
nop_90
Global Moderator
Lifer
*****
Offline Offline

Posts: 2203


View Profile
« on: April 24, 2008, 04:40:04 PM »

More for my reference
http://ivan.truemesh.com/archives/000411.html

If you are from the lisp/scheme/ruby world closures are very important
they can be done in python, but u need a few tricks

Logged
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #1 on: April 24, 2008, 04:46:19 PM »

Thanks nop, nice resource to keep around.
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
nop_90
Global Moderator
Lifer
*****
Offline Offline

Posts: 2203


View Profile
« Reply #2 on: April 24, 2008, 05:10:41 PM »

example in use
Code:
def fun(x,y):
    def adder():
        return x+y
    return adder

def fun1(n):
    a = range(n)
    def get_item():
        return a.pop()
    return get_item

class Engine(object):
    def __init__(self):
        self.callbacks = []
       
    def pump(self):
        for callback in self.callbacks :
            callback()
           
    def fun(self,n):
        def action():
            print "action %d" % (n)
        def stop():
            self.callbacks.remove(action)
        self.callbacks.append(action)
        return stop
   
e = Engine()
s1 = e.fun(10)
s2 = e.fun(100)
print "pump"
e.pump()
s1()
print "pump"
e.pump()
s2()
print "pump"
e.pump()


fun1 and fun2 are just examples not demoed
for last one engine is demoed

output is

pump
action 10
action 100
pump
action 100
pump
Logged
Pages: [1]
  Print  
 
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
cache
mart
coder
programmers
ajax
php
javascript
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks


Valid XHTML 1.0! Valid CSS!