Python Static Method
Example:
class Program:
name = “Hamza”
age = 46
@staticmethod
def my_func():
print(“Name:”, Person.name)
print(“Age:”, Person.age)
# Function call to my_func method
Program.my_func()
#Output: Name: Hamza
# Age: 46
Explanation:
name = “Hamza”: This is a field inside the Program class.
age = 46: Another field in the Program class.
Program.my_func(): Calls the static method my_func inside the Program class, which prints the values of the static fields name and age from the Program class using the class name.
Difference between a regular method and static method
Static Method | Without Static Method |
#Static method class MathOperations: #Static method: doesn’t require #’self’, operates on params only @staticmethod def add(a, b): return a + b
# Calling the static method using the #class name, without creating an object result = MathOperations.add(5, 10) print(f“Static Method Result: {result_static}“) # Output: 15 | #Regular method class MathOperations: # Regular method requires ‘self’ #and can access instance attributes def add(self, a, b): return a + b #Creating an instance of MathOperations # to use the regular method math_op = MathOperations() # Calling the regular method on the #instance result = math_op.add(5, 10) print(f“Regular Method Result: {result_regular}“) # Output: 15 |
Why to use a static method instead of a regular method?
No Need for Object Instantiation
Static methods can be called directly using the class name without creating an object of the class. This is useful when the method’s behavior does not depend on instance-specific data. It saves memory and time because you don’t need to instantiate an object.
Utility or Helper Functions
Static methods are great for utility or helper functions that perform operations independent of instance variables (objects). These methods typically perform calculations, data transformations, or other standalone tasks.
Shared Logic Across All Instances
Static methods can be used when the logic inside the method is applicable to all instances (objects) of the class equally and does not change based on the instance’s state.
Example:
Imagine you are building a User Registration System, and you need each new user to have a unique ID. You can use a counter to automatically generate and assign these IDs as users are created.
class User:
# Static property to keep track of the total number of users (this acts as our counter)
__user_count = 0
def __init__(self, name):
self.name = name
self.user_id = User.generate_user_id() # Assign a unique user ID to each user
@staticmethod
def generate_user_id():
# Increment the user count and use it as a unique ID
User.__user_count += 1
return User.__user_count
def display_user_info(self):
print(f”User ID: {self.user_id}, Name: {self.name}”)
# Creating multiple users
user1 = User(“Alice”)
user2 = User(“Bob”)
user3 = User(“Charlie”)
# Displaying user information
user1.display_user_info() # Output: User ID: 1, Name: Alice
user2.display_user_info() # Output: User ID: 2, Name: Bob
user3.display_user_info() # Output: User ID: 3, Name: Charlie
1. Utility or Helper Functions
Explanation:
In the User class, the static method generate_user_id() is a utility or helper function. It does not depend on any instance-specific data (such as name) and operates solely on class-level data (the static property __user_count). Its purpose is simple: increment the user counter and return a unique ID, which can be reused across all instances.
2. Shared Logic Across All Instances
Explanation:
The generate_user_id() method contains logic that is shared across all instances of the User class. Each time a new user is created, the method increments the static __user_count from the previous value and returns the new value as the unique ID. If we use a regular method here, everytime we create an object for different users the counter will start from 1 again whereas here it is incrementing according to previous value i.e. 1,2,3… and so on. This behavior is uniform for all users — no matter who the user is (whether it’s Alice, Bob, or Charlie), the same logic applies.
Course Video:
Course Video
Course Video English:
Task:
1. Static Field:
Create a class named MathHelper with a static field PI of type double initialized to 3.14.
Create a static method CalculateCircleArea(double radius) that calculates and returns the area of a circle using the formula PI * radius * radius.
Use the static field and method in the main method to calculate and print the area of a circle with radius 5,10 and 20.
2. Static Method:
Create a class named Utility with a static method IsPrime(int number) that checks if the given number is a prime number.
Use the static method in the main method to check and print whether numbers like 7, 12, and 23 are prime.
Task Video
YouTube Reference :
A static method in Python is a function that belongs to a class but doesn’t modify or access class or instance data.
Static type refers to methods or data that do not require object-specific context.
Static data is shared across all instances of a class.
A static method doesn’t need self, while self is used to refer to instance attributes.
@staticmethod decorator is used to define a static method.
Use static methods when the behavior doesn’t depend on object state.
Static methods are useful, but not always ideal when instance-related logic is needed.
The @staticmethod decorator marks methods that don’t need class or instance references.
@staticmethod doesn’t take cls or self, while @classmethod takes cls as the first parameter.
@staticmethod doesn’t take cls or self, while @classmethod takes cls as the first parameter.