Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Advanced Python : Static and Class Methods

19,664 views

Published on

This presentation gives introduction to static and class methods in python with simple and easy to understand examples.

Published in: Technology, News & Politics
  • can you make it downloadale please sir
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Can this slide being download-able?
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Advanced Python : Static and Class Methods

  1. 1. Static and Class Methods inPythonBhanwar Singh
  2. 2. What?• It is possible to define two kinds of methodswithin a class that can be called without aninstance – static method and class method.• This feature was introduced to new-styleclasses but it can be used for classic classes aswell.• Normally a class method is passed ‘self’ as itsfirst argument. Self is an instance object.• Basically we will modify that behavior i.e.methods will not expect ‘self’ as firstargument.
  3. 3. But..Why?• Sometimes we need to process data associatedwith classes instead of instances.• Such as keeping track of instances created orinstances currently in memory. This data isassociated to class.• Simple function written outside the class cansuffice for this purpose.• But the code is not well associated withclass, cannot be inherited and the name of themethod is not localized.• Hence python offers us static and class methods.
  4. 4. What if we try to run a method without self argument?class Spam(object):numInstances = 0def __init__(self):Spam.numInstances = Spam.numInstances + 1def printNumInstances():print("Number of instances created: ", Spam.numInstances)X = Spam()Y = Spam()Spam.printNumInstances()X.printNumInstances()But this code shows different behavior for python 2.6 and 3.0For 2.6 :None of the method call work.For 3.0:Call through class worksCall through instance does not work.
  5. 5. Static Methods• Simple functions with no self argument.• Nested inside class.• Work on class attributes; not on instanceattributes.• Can be called through both class and instance.• The built-in function staticmethod()isused to create them.
  6. 6. How to create?Class MyClass:def my_static_method():………………………………………..………………………………………..-------Rest of the code---------------------------------------------------my_static_method = staticmethod(my_static method)
  7. 7. Exampleclass Spam(object):numInstances = 0def __init__(self):Spam.numInstances = Spam.numInstances + 1def printNumInstances():print("Number of instances created: ", Spam.numInstances)printNumInstances = staticmethod(printNumInstances)X = Spam()Y = Spam()Spam.printNumInstances()X.printNumInstances()The output will be –Number of instances created: , 2Number of instances created: , 2
  8. 8. Benefits of Static Methods.• It localizes the function name in the classscope (so it won’t clash with other names inthe module).• It moves the function code closer to where itis used (inside the class statement).• It allows subclasses to customize the staticmethod with inheritance.• Classes can inherit the static method withoutredefining it
  9. 9. Class Methods• Functions that have first argument as classname.• Can be called through both class and instance.• These are created with classmethod inbuiltfunction.• These always receive the lowest class in aninstance’s tree. (See next example)
  10. 10. How to create?Class MyClass:def my_class_method(class_var):………………………………………..………………………………………..-------Rest of the code---------------------------------------------------my_class_method = classmethod(my_class_method)
  11. 11. class A:hi="Hi! I am in class "def my_method(cls):print(A.hi,cls)my_method = classmethod(my_method)class B(A):passA.my_method()B.my_method()(Hi! I am in class , <class __main__.A at 0x004A81B8>)(Hi! I am in class , <class __main__.B at 0x00540030>)OutputExampleThis behavior of class method make them suitable for data that differs in eachClass hierarchy.
  12. 12. Exampleclass Spam:numInstances = 0def count(cls): # Per-class instance counterscls.numInstances += 1 # cls is lowest class above instancedef __init__(self):self.count() # Passes self.__class__ to countcount = classmethod(count)class Sub(Spam):numInstances = 0class Other(Spam): # Inherits __init__numInstances = 0x = Spam()y1, y2 = Sub(), Sub()z1, z2, z3 = Other(), Other(), Other()print x.numInstances, y1.numInstances, z1.numInstancesprint Spam.numInstances, Sub.numInstances, Other.numInstancesOutput1 2 31 2 3

×