Methods:
- It is possible to define two kinds of methods with-in a class that can be called without an instance.
Class Method:
- A class method takes cls as first parameter.
- A class method can access or modify class state.
- We use @classmethod decorator in python to create a class method.
- We generally use class method to create factory methods.
Syntax:
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
........................
........................
........................
Static Method:
- A static method needs no specific parameters.
- A static method can’t access or modify it.
- We use @staticmethod decorator to create a static method in python.
- We generally use static methods to create utility functions.
Syntax:
class C(object):
@staticmethod
def fun( arg1, arg2, ...):
....................
....................
....................
Example:
class Test(object):
x=20
def m1(self):
print"hai,i am in instance method"
print(Test.x)
@classmethod
def m2(cls):
print "hai,i am in class method"
print(Test.x)
@staticmethod
def m3():
print "hai,i am in static method"
print(Test.x)
Test.m2()
Test.m3()
Test.m1()
No comments:
Post a Comment