0 votes
in Python by
What is Class and Static Methods in Python

1 Answer

0 votes
by

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

Related questions

0 votes
asked Jun 26, 2020 in Python by AdilsonLima
0 votes
asked Dec 22, 2019 in Python by rajeshsharma
...