Junior — Middle
How is a method that does not depend on an instance of a class declared and used in Python?
sobes.tech AI
Answer from AI
In Python, a method that does not depend on an instance of the class is declared using the @staticmethod decorator. Such a method does not take the self parameter and can be called either through an instance of the class or through the class itself.
Example:
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
# Call through the class
print(MyClass.greet("Alice")) # Outputs: Hello, Alice!
# Call through an instance
obj = MyClass()
print(obj.greet("Bob")) # Outputs: Hello, Bob!
This type of method is useful when the method's logic does not depend on the state of a specific object.