functions/methods are of two types. They are:
Class methods
Static methods
Class Methods
A method defined inside a class is bound to its object, by default.
However, if the method is bound to a Class, then it is known as classmethod.
Consider the following two examples:
Example 1 defines the method getCirclesCount, bound to an object of Circle class.
Example 2 defines the classmethod getCirclesCount, bound to class Circle.
Class Methods - Example
Example 1
class Circle(object):
no_of_circles = 0
def __init__(self, radius):
self.__radius = radius
Circle.no_of_circles += 1
def getCirclesCount(self):
return Circle.no_of_circles
c1 = Circle(3.5)
c2 = Circle(5.2)
c3 = Circle(4.8)
print(c1.getCirclesCount()) # -> 3
print(c2.getCirclesCount()) # -> 3
print(Circle.getCirclesCount(c3)) # -> 3
print(Circle.getCirclesCount()) # -> TypeError
Static Method
A method defined inside a class and not bound to either a class or an object is known as Static Method.
Decorating a method using @staticmethod decorator makes it a static method.
Consider the following two examples:
Example1 defines the method square, outside the class definition of Circle, and uses it inside the class Circle.
Example2 defines the static method square, inside the class Circle, and uses it.
Static Method - Example
Example 1
def square(x):
return x**2
class Circle(object):
def __init__(self, radius):
self.__radius = radius
def area(self):
return 3.14*square(self.__radius)
c1 = Circle(3.9)
print(c1.area())
print(square(10))
Output
47.7594
100