Tuesday, August 10, 2010

Python methods --- instance method, classmethod, staticmethod

Do you know what are the differences?
  1. instance method, must be called by an instance: d.instance_method(), demo.instance_method(d)
  2. class method(the first arg must be the class itself), can be called by class or instance: d.class_method(), demo.class_method()
  3. static method, can be called by class or instance: d.static_method(), demo.static_method()

class demo:
    def __init__(self):
        self.i=0 # i, instance variable
    def instance_method(self):
        self.i +=1
        print self.i
    @classmethod
    def class_method(cls): # cls is an instance of demo
        cls.v +=1
        print cls.v
    @staticmethod
    def static_method(s): # s, just a parameter
        s+=1
        print s
    v=0  # class variable

Result:
>>> import sys
>>> sys.path.append('/home/mengyg/Documents/pythondemo')
>>> from methods import *
>>> demo.instance_method() # instance method cann't be called by class

Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    demo.instance_method()
TypeError: unbound method instance_method() must be called with demo instance as first argument (got nothing instead)
>>> demo.v
0
>>> demo.i # instance variable, not class variable

Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    demo.i
AttributeError: class demo has no attribute 'i'
>>> demo.class_method()
1
>>> demo.static_method() # must have a parameter

Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    demo.static_method()
TypeError: static_method() takes exactly 1 argument (0 given)
>>> demo.static_method(1)
2
>>> demo.v
1
>>> d=demo()
>>> d.i
0
>>> d.v # the value of v is 1
1
>>> d.instance_method()
1
>>> d.class_method()
2
>>> d.v
2
>>> d.static_method(4)
5
>>> d.v
2
>>> d.v=3 # if the class variable is changed external, the value will be different with class itself, i don't know the reason
>>> demo.v
2
>>> demo.v=5
>>> demo.v
5
>>> d.v
3
>>> 

------------------------
Kind Regards,
Yonggang Meng

0 comments:

Post a Comment