📜  Python staticmethod()(1)

📅  最后修改于: 2023-12-03 14:46:04.494000             🧑  作者: Mango

Python staticmethod()

In Python, staticmethod() is a built-in function that is used to define a static method. The static method is a method that belongs to a class and does not have access to the class instance or class attributes. It is a method that can be called from the class without creating an instance of that class.

Syntax
class MyClass:
    @staticmethod
    def my_static_method(arg1, arg2, ...):
        # code here

The staticmethod() function can also be used outside of the class by using the method name as an argument.

class MyClass:
    @staticmethod
    def my_static_method(arg1, arg2, ...):
        # code here

MyClass.my_static_method(arg1, arg2, ...)
Example
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def is_adult(age):
        if age >= 18:
            return True
        else:
            return False

person1 = Person("John", 23)
person2 = Person("Jane", 17)

print(person1.name, Person.is_adult(person1.age))
print(person2.name, Person.is_adult(person2.age))

Output:

John True
Jane False

In this example, the is_adult() method is a static method that checks whether a person is an adult based on their age. This method does not access any class attributes, and it does not require an instance of the class. It can be called directly from the class.

Conclusion

In conclusion, the staticmethod() function is a useful tool for creating methods that do not depend on the class instance or class attributes. It is a great way to organize your code and make it more readable. You can use this function to define static methods both inside and outside of classes.