Wednesday, April 29, 2015

Understanding staticmethod classmethod Decorators

I've been using python from a while but and i've came across these terms but didn't find them where to use.I've been learning Java for a while,now suddenly all these python terms started to make a sense.

class Hello(object):
 """Understanding @staticmethod, @classmethod decorators"""

 def main(i):
  """ Using @staticmethod decorator.There is no self argument"""
  print("I'm inside main method which has @staticmethod decorator")

 def func2(self,i):
  """ using @classmethod You need to provide a self argument """
  print("I'm inside func2 method which has @classmethod decorator")

 def func3(self,i):
  print("I'm inside func3 method which has no decorator  so to acess func3 I need to create an instance of Hello class to access the methods of Hello class")
Hello.main(1) #didn't create any instanc of Hello class,yet able to access the methods 
#Hello.func3(1) ==> This will be an error. General way to acess methods is to create an instance of object 
hello_object = Hello() # Created an instance of Hello class

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

No comments:

Post a Comment