Is it possible to have static methods in Python?
Is it possible to have static methods in Python?
Yes, it is indeed possible to have static methods in Python. Static methods in Python are methods that are bound to a class rather than its instances. They do not require an instance of the class to be called and do not have access to the instance (self
) or the class (cls
) itself. Static methods are defined using the @staticmethod
decorator, which is applied to a function defined inside a class[1][2][4][5][6].
Here is a simple example of how a static method is used in Python:
class Calculator:
@staticmethod
def add_numbers(x, y):
return x + y
# Static method can be called using the class name
result = Calculator.add_numbers(5, 3)
print(result) # Output: 8
In this example, add_numbers
is a static method, which takes two parameters and returns their sum. Notice that there is no self
or cls
parameter in the method, indicating that it does not modify or access the class state or instance state.
Static metho...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào