Class Methods in Python
Table of Content:
You have read about function, higher order function, closures etc. Now, it is time to learn about their scope. Based on the scope
, 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 ofCircle
class. -
Example 2 defines the classmethod
getCirclesCount
, bound to classCircle
.
-
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
Class Methods - Example
Output of Example 1
3 3 3 TypeError: getCirclesCount() missing 1 required positional argument: 'self'
-
In Example 1,
getCirclesCount
method is bound to objects ofCircle
. -
Hence when calling it,
-
on objects
c1
, andc2
resulted in3
. -
on class
Circle
with objectc3
as argument resulted in3
again. -
on class
Circle
without any object information resulted inTypeError
.
-
Class Methods - Example
Example 2
class Circle(object): no_of_circles = 0 def __init__(self, radius): self.__radius = radius Circle.no_of_circles += 1 @classmethod def getCirclesCount(self): return Circle.no_of_circles c1 = Circle(3.5) c2 = Circle(5.2) c3 = Circle(4.8)
-
In Example 2,
getCirclesCount
is decorated withclassmethod
. -
Thus making it a class method, which bounds to class
Circle
.
Class Methods - Example
Example 2...
print(c1.getCirclesCount()) # -> 3 print(c2.getCirclesCount()) # -> 3 print(Circle.getCirclesCount()) # -> 3
Output of Example 2
3 3 3
- In Example 2, class
Circle
is passed as argument togetCirclesCount
in both cases. i.e when it is called on objects and the class.