Monday, February 8, 2010

Python: Different types of member methods

In Python classes we can have the following methods:
  1. Instance Methods
  2. Static Methods
  3. Class Methods

- Instance Methods
=====================
These are methods which are invoked upon an instance (object) of the class.
For example:

class MyClass:
    def myInstanceMethod(*args):
 print "inside myInstanceMethod, the arguments are:"
        for v in args:
            print v

Using this code we get:
>>>m = MyClass()
>>>m.myInstanceMethod()
    inside myInstanceMethod, the arguments are:
    <__main__.MyClass instance at 0xb7395a0c>

Which shows us that the object instance (commonly referred to as 'self') was passed into the instance method

If we try to call an instance method without an instance, we get:
>>>MyClass.myInstanceMethod ()
    TypeError: unbound method myInstanceMethod() must be called with MyClass instance as first argument (got nothing instead)


- Static Methods
=====================
In C++, static methods are usually used to fetch private static data from a class. The most common example is a static member which is incremented each time the constructor is called. This static member will then record the total number of instantations of the class.
In Python, the static method looks like this:

class MyClass:
    @staticmethod
    def myStaticMethod(*args):
 print "inside myStaticMethod, the number of arguments is ", len(args)
        for v in args:
            print v

Using this code we get:
>>>m = MyClass()
>>>m.myStaticMethod ()
     inside myStaticMethod, the number of arguments is  0
>>>MyClass.myStaticMethod ()
     inside myStaticMethod, the number of arguments is  0

The main difference in Python between the instance and static methods is that the static methods can be called by both instances and the class itself

- Class Methods
=====================

class MyClass:
    @classmethod
    def myClassMethod(*args):
        print "inside myClassMethod, the number of arguments is ", len(args)
        for v in args:
            print v

Using this code we get:
>>>m = MyClass ()
>>>m.myClassMethod ()
inside myClassMethod, the number of arguments is  1
__main__.MyClass

>>>MyClass.myClassMethod ()
inside myClassMethod, the number of arguments is  1
__main__.MyClass

Here we see (like the instance methods) we receive 1 argument, unlike the instance methods, the argument is the type of class, in the instance methods we received an object which was bound to the class.

No comments: