Sunday, January 31, 2016

class method in details

class method in details

In python class method invocation should be done with care because it is little different from Java.

3 types of method can be defined in a class
1. Instance method: This methods are the method for which class instance is passed implicitly as an argument. 
2. Class method: This methods are the method for which caller class is passed implicitly as an argument. 
We need to use decorator @classmethod to define this inside a class.
3. Static method: This methods are the method for which neither class nor instance is passed implicitly as an argument. 
We need to use decorator @staticmethod to define this inside a class.

In below I have given one example class.

===start of class_example.py==
class A:
   def __init__(self,name,org='init_xyz'):
      print "start constructor"
      self.name=name
      self.org=org
      self.age=10
      print "end constructor"

   def instanceMethod(self):
      print "start of instanceMethod"
      print self.name,self.org
      print "End of instanceMethod"
   @classmethod
   def class_method(ownClass, cls):
      print "start class_method"
      print cls.name,cls.org
      print "End of class_method"

   @staticmethod
   def static_method(name,org='static_xyz'):
      print "start static_method"
      print name,org
      print "End of static_method"


a=A('james')
print "output of instanceMethod: calling using instance..."
a.instanceMethod()
b=A('Thor','ABC')
print "output of class_method: calling using syntax a.methodName(...)"
a.class_method(b)

print "output of class_method: calling using syntax A.methodName(a,...)"
A.class_method(b)
====end of class_example.py==

Output:
[root@xxxx pyws]# python class_example.py
start constructor
end constructor
output of instanceMethod: calling using instance...
start of instanceMethod
james init_xyz
End of instanceMethod
start constructor
end constructor
output of class_method: calling using syntax a.methodName(...)
start class_method
Thor ABC
End of class_method
output of class_method: calling using syntax A.methodName(a,...)
start class_method
Thor ABC
End of class_method



No comments:

Post a Comment