×

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods. So methods are a piece of code that can be reused in any program we do. There are mainly three different types of methods they are:

  • Instance method
  • Class method
  • Static method

In this article, we will discuss the class method and static methods in python. Lets us also learn about the differences between them and the usage of these methods.

The class method in python:

The @class method decorator is a built-in function. Once the function is defined, this method gets evaluated and covers the full function after evaluation. A class method will receive the class as an implicit argument. And the syntax for this method is given as follows

class c(object):
     @classmethod
      Def fun(cls, arg1, arg2, arg3, ….):

 Here the fun is a function that needs to get converted into a class.

  • A Class method is one of the method that is completely used to the class but not the object of the class.
  • They have access to the state of the class because it takes a class parameter that refers to the class and the object instance.
  • A class state could be modified, which would apply across all other class instances.

Static method in python:

In the static method, we don't get any implicit first argument. The static method is also needed to the class but not with the object of that class. With this method, we can't access or modify any class state. The static method is present in a class because it makes a meaning for the method to be present in a class. The syntax used for this method is given as follows

class c(object):
	@staticmethod
	def fun(arg1, arg2, arg3, …..):

with this, we will get a static method for the fun function.

How do we define a class method and a static method:

As discussed above, we use the @classmethod decorator and @staticmethod decorator to implement class and static methods. Let us have a look and understand this concept by taking an example code where we use a static method to check whether the person is an adult or a child. As python doesn't support method overloading, unlike other programming languages, we take the class methods to create a person's object from his birth year. Let us look at the example code:

Code:

# program to understand the use of the class method and static method.
from datetime import date
 
 class Person:
    def __init__(self, pname, age):
        self.pname = pname
        self.age = age
 
    # using a class method to create a Person by taking their birth year.
    @classmethod
    def from_birthyear(cls, pname, year):
        return cls(pname, date.today().year - year)
 
    # using a static method to check wether a Person is an adult or not.
    @staticmethod
    def isAdult(age):
        return age > 18
 
 
personx = Person('varun', 19)
persony = Person.from_birthyear('srinivas', 1974)
 
print(personx.age)
print(persony.age)
 
# print the result
print(Person.isAdult(25))

Output:

19
48
True

Explanation:

So in this program, we first imported the required packages and then created a class and gave its attributes. Next, we used a class method to create a person by using the object's birth year. Then we used the static method to check wether a person was an adult or not. Then we were given the input and output; after execution, we got this output.

So we generally use the class methods while creating factory methods, and the factory method will return the class object for different cases. And static methods are used when they create utility functions.

The difference between the static and class methods are:

  • A class method needs parameters while taking a class, but the static method doesn't require any parameters.
  • A class method can modify any class state, whereas a static method has no access to modify the class state.
  • Static Methods are not involves in the class state. But they only work on utility-type methods.
  • To create class methods in python, we use @classmethod decorator, whereas to create a static method in python, we use @staticmethod decorator.

Conclusion:

So far in this article, we have learned about python methods where static and class methods are thoroughly discussed using example codes and basic syntaxes.


Related Topics

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python Num2words

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

Difference between Module and Package in Python

The main difference between the module and the package in Python is that the module can be a simple file in Python that contains the different functions and collection of...

4 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 minutes read.

Cx_Oracle Python with Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Raise Exception in Python

Most of the programmers/developers create large programs to solve complex tasks in Python. The code can be of 1000 lines and even more based on the need of the problem....

5 minutes read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Python Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.