[Baypiggies] Discussion for newbies/beginner night talks
Shannon -jj Behrens
jjinux at gmail.com
Wed Feb 14 01:42:05 CET 2007
#) Unlike a lot of languages, Python has a nice *mix* of the
programming paradigms. It's not just OO. You should embrace this.
Let me run down the list with some examples:
Procedural:
Code everything in functions. You can put functions inside of
functions and lexical scoping works like in Pascal.
Functional:
>>> l = [1, 2, 3, None, 1.2]
>>> filter(None, l)
[1, 2, 3, 1.2]
>>> l = [1, 2, 3]
>>> filter(lambda x: x > 2, l)
[3]
>>> map(str, l)
['1', '2', '3']
>>> # A closure.
>>> def greeter(name):
... def greet():
... print "Hello, my name is %s" % name
... return greet
...
>>> greet = greeter('JJ')
>>> greet()
Hello, my name is JJ
>>> # Now I can pass my special greet somewhere else.
Modern functional programming a la Haskell:
>>> l = [1, 2, 3, None, 1.2]
>>> [i for i in l if l is not None]
[1, 2, 3, None, 1.2]
>>> l = [1, 2, 3]
>>> [i for i in l if i > 2]
[3]
>>> [str(i) for i in l]
['1', '2', '3']
Object oriented:
>>> class Fruit:
... def good_for_you(self):
... return True
...
>>> class Orange(Fruit):
... def taste(self):
... return "sweet"
...
>>> class Lemon(Fruit):
... def taste(self):
... return "sour"
...
>>> fruit = [Orange(), Lemon()]
>>> for i in fruit:
... print i.__class__.__name__
... print i.good_for_you()
... print i.taste()
...
Orange
True
sweet
Lemon
True
sour
But unlike Java, we have bound methods:
>>> taste = Orange().taste
>>> # I can now pass taste around as a function pointer.
...
>>> taste()
'sweet'
Imperative:
a = 0
a += 1 # That's a functional programming joke ;)
Aspect oriented programming:
>>> # Functions:
...
>>> def sum(a, b):
... print a + b
...
>>> # Aspects:
...
>>> def wrap_function(f):
... def inner(*args, **kargs):
... print "Calling %s with %r %r" % (
... f.func_name, args, kargs)
... return f(*args, **kargs)
... return inner
...
>>> # Weave them together:
...
>>> sum = wrap_function(sum)
>>>
>>> # Test:
...
>>> sum(1, 2)
Calling sum with (1, 2) {}
3
Logic-based:
Here's a Python-take on Prolog:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303057
Ok, I'm out of paradigms ;)
Happy Hacking!
-jj
More information about the Baypiggies
mailing list