Every non static method has an implicit parameter called that refers to the object in memory

In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python.

The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as an implicit first argument, just like an instance method receives the instance 



Syntax Python Class Method: 

class C(object): @classmethod def fun(cls, arg1, arg2, ...): .... fun: function that needs to be converted into a class method returns: a class method for function.
  • A class method is a method that is bound to the class and not the object of the class.
  • They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
  • It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that will be applicable to all the instances.

What is the Static Method in Python?

A static method does not receive an implicit first argument. A static method is also a method that is bound to the class and not the object of the class. This method can’t access or modify the class state. It is present in a class because it makes sense for the method to be present in class.

Syntax Python Static Method: 

class C(object): @staticmethod def fun(arg1, arg2, ...): ... returns: a static method for function fun.

Class method vs Static Method

The difference between the Class method and the static method is:

  • A class method takes cls as the first parameter while a static method needs no specific parameters.
  • A class method can access or modify the class state while a static method can’t access or modify it.
  • In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
  • We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.

When to use the class or static method?

  • We generally use the class method to create factory methods. Factory methods return class objects ( similar to a constructor ) for different use cases.
  • We generally use static methods to create utility functions.

How to define a class method and a static method?

To define a class method in python, we use @classmethod decorator, and to define a static method we use @staticmethod decorator. 
Let us look at an example to understand the difference between both of them. Let us say we want to create a class Person. Now, python doesn’t support method overloading like C++ or Java so we use class methods to create factory methods. In the below example we use a class method to create a person object from birth year.

As explained above we use static methods to create utility functions. In the below example we use a static method to check if a person is an adult or not. 

Below is the complete Implementation 

from datetime import date

    def __init__(self, name, age):

    def fromBirthYear(cls, name, year):

        return cls(name, date.today().year - year)

person1 = Person('mayank', 21)

person2 = Person.fromBirthYear('mayank', 1996)

print(Person.isAdult(22))

Output:

21 25 True

Article Tags :

In every programming language, memory is a vital resource and is also scarce in nature. Hence it’s essential that the memory is managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtual Machine(JVM) is an engine that provides a run time environment to drive the java code. It converts the java byte code into machine language. The JVM has two primary functions. They are:

  1. It allows java programs to run on any device or OS to fulfil WORA (Write Once Run Anywhere) principle.
  2. It manages and optimizes program memory.

The JVM memory manager creates memory pools during the runtime of the program. Let’s understand the concept of memory pools in java. There are two types of memory pools namely the stack memory and the heap memory. The main difference between stack memory and the heap memory is that the stack is used to store only the small datatypes whereas heap stores all the instances of the class. And, since java either implicitly or explicitly extends the class from Object.class, every class we create is a collection of objects. This also means that we cannot use a method or a variable unless we instantiate it with a new keyword. As soon as we instantiate the methods, JVM allocates some memory on the heap and it stores the address of the instance on the stack. After this, the methods and variables can be used. In order to get a better understanding of how the new keyword works, let’s take an example. Let’s take a bird class. Whenever a new bird is found, the number of birds need to be incremented. Let’s try to implement this code: 



    public static void main(String args[])

        Bird b1 = new Bird("Parrot");

        Bird b2 = new Bird("Sparrow");

        Bird b3 = new Bird("Pigeon");

        System.out.println(b1.getNumber());

Clearly, this method cannot be used to count the number of birds because at every instance, a new heap is being allocated and for all the instances, the number of birds is being initialized from 0 and is incremented to 1. Therefore, we are creating three independent birds where, in every bird object, the number of birds is 1. In order to avoid this, we initialize the methods and variables as static. This means that the variable or method is not changed for every new object creation. Since these methods and variables cannot be stored in a normal heap, they are stored in a special area called permanent generation(PermGen).

The main difference is that the heap is the auto growing space, with RAM memory as its constraints, whereas this PermGen has a fixed space allocation, and this is shared with all the instances.

Let’s implement this by changing the number to a static variable. 

    private static int number;

        System.out.println("This bird flies");

    public static void main(String args[])

        Bird b1 = new Bird("Parrot");

        Bird b2 = new Bird("Sparrow");

        Bird b3 = new Bird("Pigeon");

        System.out.println(b1.getNumber());

Note: In Java 5 and 6, PermGen space was used. But due to major changes in memory model in Java 8, storage specification has also been changed. Now a new memory space “MetaSpace” has been introduced where all the names fields of the class, methods of a class with the byte code of methods, constant pool, JIT optimizations are stored. The main reason for this change of PermGen in Java 8.0 is that it is tough to predict the size of PermGen, and it helps in improving garbage collection performance.


Article Tags :

Chapter 7 Objects and Classes

Using Classes and Objects. Chapter

Chapter 3. Using Classes and Objects

Chapter 3: Using Classes and Objects

Lecture 4. Classes and Objects

Classes and objects in Scala

Introduction to Classes and Objects

Lesson 15..Classes and Objects

Java Classes, Objects, and Events: A Preview

3.2 Classes, Objects, Methods and Instance Variables

Graphical Objects and User Interfaces Chapter 3-8

Chapter 10 File Systems and Mobile Objects

Chapter 11 Abstract Classes and Interfaces

Chapter 13. Abstract Classes and Interfaces

Chapter 13 Abstract Classes and Interfaces

Chapter 5 Generic Classes and Methods

Última postagem

Tag