@staticmethod
Thu Feb 22 2024 15:57:47 GMT+0000 (Coordinated Universal Time)
Saved by
@aguest
#python
#classes
class Dates:
def __init__(self, date):
self.date = date
def get_date(self):
return self.date
@staticmethod
def format_date_with_dashes(date):
# Replace / with -
return date.replace("/", "-")
slash_date = "10/20/2024"
# Calling format_date_with_dashes() like any other function, but preceded by it's class name
dash_date = Dates.format_date_with_dashes(slash_date)
print(dash_date) # 10-20-2024
content_copyCOPY
The `staticmethod()` function returns a static method for a given function.
Static methods are methods that are bound to a CLASS rather than to an instance of a class. They DO NOT require a class instance to be created before they can be used.
Static methods do NOT take a first parameter of `self` since they don't operate on an instance of a class. You can call them like normal functions, but you need to precede the method name with the class name (`Dates.format_date_with_dashes()`).
`staticmethod` is generally used for helper functions inside of a class that can be called whenever needed without needing to create an instance of that class.
https://www.programiz.com/python-programming/methods/built-in/staticmethod
Comments