×

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

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

File Explorer using Tkinter in Python

File Explorer: Users can control folders and files on a device using an application known as a file manager or file explorer. Customers can access, edit, copy, delete, and start moving files...

3 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

Anaconda python 3.7 download for windows 10 64-bit

Before installing Anaconda, you need to first know what Anaconda actually is. Anaconda is an IDE (Integrated development environment) platform used to code and executes python programs. Anaconda works both online...

3 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

2 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 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.

Cross Validation in Sklearn

Data scientists can benefit from cross-validation in machine learning in two key ways: it can assist in minimising the amount of data needed and ensure the artificial intelligence model is...

14 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Python Struct

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.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Python Static Method

Introduction to methods that are majorly used in Python: Class MethodsInstance MethodsStatic Methods Before going to the in-depth concept of Static Methods, let us briefly discuss Class Methods and Instance Methods. Class Methods The...

4 minutes read.

Python isinstance() function

Python isinstance() function The isinstance() function in Python returns a Boolean value ‘True’ if the given object is of the specified type, otherwise it returns False. Syntax isinstance(object, classinfo) Parameter object: It is a required parameter which represents an object. classinfo: This...

1 minute read.

Python String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.