Junior — Middle
How can a static method be called inside a class or from outside its context?
sobes.tech AI
Answer from AI
In Python, a static method is declared using the @staticmethod decorator. It can be called both inside the class and outside, using either the class name or an instance.
Example:
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
# Call inside the class (e.g., from another method)
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
def welcome(self):
return MyClass.greet("Alice")
# Call outside the class
print(MyClass.greet("Bob"))
obj = MyClass()
print(obj.greet("Charlie")) # also works, but it's preferable to call via the class
Thus, a static method does not depend on an instance and does not take the self parameter.