staticmethod()

staticmethod to get static method for a given functions.

By using classmethod(), we work with class , whereas staticmethod() has nothing to do with class.

Example:

class animals():
    def __init__(self,name,height):
        self.name= name
        self.height=height
    
    def legs(no_legs):
        print("legs: ",no_legs) 
animals.legs=staticmethod(animals.legs)        
animals.legs(4)
Output
legs : 4

Using isinstance()

By using isinstance() we can check if the object is instance of the class or not.

Difference Between staticmethod() and classmethod()

A static method doesn't access or modify the class state, while a class method works with the class itself:

class Sample:
    @staticmethod
    def static_method():
        print("No class data used.")

    @classmethod
    def class_method(cls):
        print("Class data can be used here.")

Use Case: Utility Functions Inside a Class

Static methods are useful for grouping utility functions that don't need access to instance variables:

class MathOperations:
    @staticmethod
    def add(x, y):
        return x + y
print(MathOperations.add(5, 10))  # Output: 15

Static Method for Validation

Static methods are great for utility tasks like validation:

class Validator:
    @staticmethod
    def is_valid_age(age):
        return 0 < age < 120
print(Validator.is_valid_age(25))  # Output: True

Use Case: Factory Method for Object Creation

Static methods can be used to create specific objects without accessing class data:

class AnimalFactory:
    @staticmethod
    def create_dog():
        return "Dog created"
print(AnimalFactory.create_dog())  # Output: Dog created


All Built in Functions in Python locals() dir() ord()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer