Python

Polymorphism

Polymorphism comes from two Greek words meaning ‘many shapes’ and is best explained by a real world example. The feet of a human are a very different shape to that of a centipede, but they have basically the same function, walking. So we can refer to the feet of a human, centipede, horse, or frog without confusion. Polymorphism allows the programmer to give the same names to methods and attributes that play similar roles in distinctive classes.
As an example we will use a built-in operator, function or method on an object without knowing what kind of object it is.

Tags:

Lambda Expressions

This is a small function with no name that contains an expression and returns its result. We will use it in the built in function filter: filter(function, iterable).

>>> numbers = [1,2,3,4,5,6,7,8,9,10]
>>> filter(lambda n: n % 2 == 0, numbers)
[2, 4, 6, 8, 10]
>>>

Tags:

Recursion

This is where a function calls itself. Let’s look at a classic example of recursion, the power of something. First we define the problem:

power(x, 0) is 1 for all numbers x.
power(x, n) for n > 0 is the product of x and power(x, n-1).

def power(x, n):
if n == 0:
return 1
else:
return x * power(x, n-1)

Tags:

Pages 