Thursday 30 July 2015

DIFFERENCE BETWEEN @STATICMETHOD AND @CLASSMETHOD IN PYTHON

@classmethod
To pass class as argument instead of instance(self). We could have achieved this by creating function out of class and passing that class as argument but that could raise mentainance problem in future. So to overcome this Python2.2 came up with @classmethod.

1) Maintainance Problem Causing Senario
def get_no_of_instance(ins_obj):
    return ins_obj.__class__.no_inst

class Test(object):
    no_inst = 0

    def __init__(self):
        Test.no_inst = Test.no_inst + 1

inst1 = Test()
inst2 = Test()

print get_no_of_instance(inst1)  # will output 2

2) Implementation using @classmethod
class Test(object):
    no_inst = 0

    def __init__(self):
        Test.no_inst = Test.no_inst +1

    @classmethod
    def get_no_of_instance(test_class):
        return test_class.no_inst

inst1 = Test()
inst2 = Test()

print inst1.get_no_of_instance() # will output 2
print Test.get_no_of_instance()  # will output 2

So calling @classmethod either by instance or by Class it'll pass the same argument to @classmethod.

@staticmethod
Sometimes we don't need instance method but the normal method, to access those methods we need to decorate them with @staticmethod. It's implementation is same as @classmethod but we don't pass class as argument to method. Without using decorator also we could have achieved this by creating function outside of class but it would have raised maintainance issue in future as code was increased.

1) Maintainance Problem Causing Senario
def checkTOF():
    return true

class Test(object):
    def __init__(self,data):
        self.data = data

    def play1(self):
        if checkTOF():
            print 'play one data is ',self.data

test = Test(10)
test.play1()   

2) Implemenatation using @staticmethod
class Test(object):
    def __init__(self,data):
        self.data = data

    @staticmethod
    def checkTOF():
        return 'true'

    def play1(self):
        if self.checkTOF():
            print 'play one data is ',self.data

test = Test(10)
test.play1()

So this way can bring all related code at one class.

No comments:

Post a Comment