Python staticmethod() Built in Function

The staticmethod() function in Python returns a static method for a given function. A static method is a method that does not require an instance of the class or the class itself as an argument. The syntax is:

staticmethod(function)

where function is any callable object that can be invoked without an object or a class.

Here are some examples of using staticmethod() with different functions:

# Define a function outside a class
def hello(name):
    print(f"Hello, {name}!")


# Use staticmethod() to create a static method
hello = staticmethod(hello)

# Call the static method without an object or a class
hello("Alice") # Output: Hello, Alice!

# Define a class with a static method
class Mathematics:

    # Use @staticmethod decorator to declare a static method

    @staticmethod
    def addNumbers(x, y):
        return x + y


# Call the static method using the class name
print(Mathematics.addNumbers(5, 10)) # Output: 15

# Call the static method using an object of the class
math = Mathematics()
print(math.addNumbers(3, 7))
# Output: 10

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions