Why do we use @staticmethod?

The reason to use staticmethod is if you have something that could be written as a standalone function (not part of any class), but you want to keep it within the class because it’s somehow semantically related to the class. (For instance, it could be a function that doesn’t require any information from the class, but whose behavior is specific to the class, so that subclasses might want to override it.) In many cases, it could make just as much sense to write something as a standalone function instead of a staticmethod.

Your example isn’t really the same. A key difference is that, even though you don’t use self, you still need an instance to call static_add_one — you can’t call it directly on the class with test2.static_add_one(1). So there is a genuine difference in behavior there. The most serious “rival” to a staticmethod isn’t a regular method that ignores self, but a standalone function.

Leave a Comment