![]() |
VOOZH | about |
Python staticmethod() function is used to convert a function to a static function. Static methods are independent of class instances, meaning they can be called on the class itself without requiring an object of the class.
Example:
Hello, Vishakshi!
Explanation:Utility class has a static method msg() that doesn’t need an object to work. It simply takes a name and returns "Hello, {name}!". Since it's a static method, we can call it directly using Utility.greet("Vishakshi") without creating an instance of the class.
staticmethod(function)
In object-oriented programming (OOP), a static method is a method that belongs to the class rather than an instance of the class. It is defined using the @staticmethod decorator and does not have access to instance-specific attributes (self) or class-specific attributes (cls).
Key characteristics of statics methods:
Static methods are useful in situations where a function is logically related to a class but does not require access to instance-specific data. Common use cases include:
17
Explanation:MathUtils class has a static method add() that doesn’t need an object to work. It simply takes two numbers, adds them and returns the result.
If a method does not use any class properties, it should be made static. However, methods that access instance variables must be called via an instance.
3 -1
Explanation:
Static methods cannot access instance attributes but can access class-level variables.
80
Explanation: class variable num (40) is shared across instances. The static method double() directly accesses it and returns twice its value. Since it's static, we call it without creating an instance.
Geeks, For Geeks
Explanation: Formatter class has a static method format_name() that takes a first and last name and returns them in "LastName, FirstName" format.
Hello, Vishakshi!
Explanation: Using @staticmethod is the preferred approach as it enhances readability and follows Python's best practices. However, staticmethod() is still useful in cases where decorators are not an option (e.g., dynamically assigning methods).