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


>>> test.test1(a,2)

>>> print a.n



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).


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

The WordPress.com Blog

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

%d bloggers like this: