Monthly Archives: March 2012

Special method attributes in Python

Special method attributes in python provides much of the same functionality when using ‘operator overloading’ to apply built-in operators to user defined classes.

This can be understood by the following example using classes and objects in python.

>>>class test:

. . .      def __init__(self, n):

. . .          self.n = n

. . .      def test1(self, n):

. . .          self.n = n

. . .

>>> a = test(1)

>>> print a.n

1

>>> test.test1(a,2)

>>> print a.n

2

>>>

The method ‘__init__’ is a ‘special method’ which is automatically called when an object is being created. Now, when we call test.test1(a,2), we are actually calling a method belonging to class foo with the object ‘a’ as the first parameter. This parameter is usually called ‘self’.

The following are some of the python special methods (attribute access):

object.__getattr__(self,name):- Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). object.__setattr__(self,name,value):- Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary).

If __setattr__() wants to assign to an instance attribute, it should not simply execute self.name = value — this would cause a recursive call to itself. Instead, for new style classes, it should call the base class method with the same name, for example, object.__setattr__(self, name, value). For classic classes, it should insert the value in the dictionary of instance attributes, e.g., self.__dict__[name] = value.
object.__delattr__(self,name):- Like __setattr__() but for attribute deletion instead of assignment. This should only be implemented if del obj.name is meaningful for the object. object.__getattribute__(self,name):- This method is for new style classes only. Called unconditionally to implement attribute accesses for instances of the class.

In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

Advertisements

Functional programming in Python

Python supports functional programming paradigm which treats computation as mathematical evaluation of functions. Functions are first-class objects in Python. That is they have attributes and can be referenced and assigned to variables. Python also supports higher-order functions, that can accept other functions as arguments and return functions to the caller.

The functional programming paradigm encourages us to structure our programs as collections of pure functions. The basic element of Functional programming in python are the functions map(),reduce(),and filter() , and the operator lambda.

Lambda

Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called “lambda”.The lambda definition does not include a “return” statement — it always contains an expression which is returned. Also we can put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all.

Syntax:  lambda argument_list:expression

The following shows an example of lambda function:

>>> def increment(n):
. . .       return lambda x: x + n
. . .
>>> a = increment(2)
>>> b = increment(5)
>>>
>>> print a(10), b(4)
12  9
>>>
>>> print increment(11)(12)
23
>>>

filter()

Syntax: filter(function, sequence)
filter() return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.

The following shows an example of filter():

>>> def even(num):
. . .       return num % 2 == 0
. . .
>>> n = [1,2,4,7,3,9,8,6]
>>> filter(even, n)
[2, 4, 8, 6]
>>>

map()
map() return a list of the results of applying the function to the items of the argument sequences. If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence).

>>> def test(x):
. . .       return (x*x)+x+10
. . .
>>> map(test, [1,2,3,4,5])
[12, 16, 22, 30, 40]
>>>

reduce()

reduce() function reduces a list to a single value by combining elements via a supplied function. It returns only a single value. The following function describes working of reduce() function.First it take the first two elements in the list and applied it to the function, in the next step the result of the previous step and the next element is applied to the function, this process will continue at the end of the list, finally a single value returned.

>>> l = [1,2,3,4,5]
>>> def mul(a,b):
. . .       return a*b
. . .
>>> reduce(mul, l)
120
>>>

The WordPress.com Blog

The latest news on WordPress.com and the WordPress community.