Categories: python

Static Keyword in Python

Class or Static Variables:

In Python, a variable declared within a class but outside any method is referred to as a class or static variable. A class or static variable can be referred to, but not directly through an instance.

Class or static variables are distinct from and do not conflict with other member variables of the same name.

Characteristics of Static Variables:
  • When a class object is created for the first time, static variables are allocated memory once.
  • Static variables are created outside of methods but inside a class
  • Static variables can be accessed through a class but not directly with an instance.
  • The behavior of static variables does not vary depending on the object.
Example:

class Student:
 stream = 'Science'     # Class Variable
 def __init__(self,name,roll):
  self.name = name   # Instance Variable
  self.roll = roll   # Instance Variable

# Objects of Student class
a = Student('Rohan', 54)
b = Student('Shikha', 23)

print(a.stream)
print(b.stream) 
print(a.name) 
print(b.name) 
print(a.roll) 
print(b.roll) 

# Class variables can be accessed using class
# name also
print(Student.stream) 

# Now if we change the stream for just a it won't be changed for b
a.stream = 'Commerce'
print(a.stream) 
print(b.stream) 

# To change the stream for all instances of the class we can change it
# directly from the class
Student.stream = 'Arts'

print(a.stream) 
print(b.stream) 
Output:
Science
Science
Rohan
Shikha
54
23
Science
Commerce
Science
Commerce
Arts
Static Methods:

Python includes a class-specific static method. It functions similarly to a static variable that is bound to the class rather than the class’s object. A static method can be called without creating an object for the class. This means we can use the class name to directly call the static method. Furthermore, because a static method is bound to a class, it cannot change the state of an object.

There are two ways to define a static method in Python:

  • Using the staticmethod() Method
  • Using the @staticmethod Decorator
Example: using @staticmethod
class Animal:
    
    @staticmethod
    def info(msg):
        # show custom message
        print(msg)
        print("This class is used for representing different Animal.")

Animal.info("Entering to Animal class")
Output:
Entering to Animal class
This class is used for representing different Animal.

@staticmethod is a more modern approach to defining static method

Example: usingstaticmethod()
class Animal:
    
    def info(msg):
        # show custom message
        print(msg)
        print("This class is used for representing different Animal.")
Animal.info = staticmethod(Animal.info)
Animal.info("Entering to Animal class")
Output:
Entering to Animal class
This class is used for representing different Animal.

Here, the info method is declared as a static method outside the class using the staticmethod() function approach.

Note: also read about Polymorphism in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago