Static Method & Class Method in Python

Generally we have two types of methods in Python classes, Out of that one type of method we should  call with instance of particular class, and second  one will call without instance of class.

For writing Static and Class methods in Python we have to use them with as decorator.

The most used methods in classes are instance methods, i.e instance is passed as the first argument to the method.

For example, a basic instance method would be as follows:

class Kls(object):
    def __init__(self, data):
        self.data = data
    def printd(self):
        print(self.data)
ik1 = Kls(‘arun’)
ik2 = Kls(‘seema’)
ik1.printd()
ik2.printd()
This gives us the following output:
arun
seema
Here self is the current instance of particular class, here we have written a simple method which calls by self as the first argument.
There are some methods which don’t requires any instance to call that particular method.
Static Method:
Simple Method or Function which doesn’t requires any self argument,Static Method will have access only class level attributes but not instance level attributes.
It can be called by both object as well as class.
class myclass(object):
a = 20
def __init__(self):
print ” i am constructor”
@staticmethod
def static():
print ” i am static method”
now by using class name can call it
myclass.static()
out:i am static method
Class Method:
Simple Method or Function which requires class as the first argument.
By using this method can access all class attributes via class argument
class myclass(object):
a = 40
def __init__(self):
b = 90
print ” i am constructor”
@classmethod
def class1(clas):
print ” i am class method”
now by using class name can call it
myclass.class1()
out:i am class method
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s