• Save
Advanced Python : Static and Class Methods
Upcoming SlideShare
Loading in...5
×
 

Advanced Python : Static and Class Methods

on

  • 4,721 views

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

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

Statistics

Views

Total Views
4,721
Views on SlideShare
4,721
Embed Views
0

Actions

Likes
3
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

CC Attribution License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods Presentation Transcript

    • Static and Class Methods inPythonBhanwar Singh
    • 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.
    • 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.
    • 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.
    • 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.
    • How to create?Class MyClass:def my_static_method():………………………………………..………………………………………..-------Rest of the code---------------------------------------------------my_static_method = staticmethod(my_static method)
    • 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
    • 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
    • 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)
    • How to create?Class MyClass:def my_class_method(class_var):………………………………………..………………………………………..-------Rest of the code---------------------------------------------------my_class_method = classmethod(my_class_method)
    • 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.
    • 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