Let's say I have a class and would like to implement a method which creates an instance of that class. What I have is 2 options:
- static method,
- class method.
An example:
class DummyClass:
def __init__(self, json):
self.dict = json
@staticmethod
def from_json_static(json):
return DummyClass(json)
@classmethod
def from_json_class(cls, json):
return cls(json)
Both of the methods work:
dummy_dict = {"dummy_var": 124}
dummy_instance = DummyClass({"test": "abc"})
dummy_instance_from_static = dummy_instance.from_json_static(dummy_dict)
print(dummy_instance_from_static.dict)
> {'dummy_var': 124}
dummy_instance_from_class = DummyClass.from_json_class(dummy_dict)
print(dummy_instance_from_class.dict)
> {'dummy_var': 124}
What I often see in codes of other people is the classmethod design instead of staticmethod. Why is this the case?
Or, rephrasing the question to possibly get a more comprehensive answer: what are the pros and cons of creating a class instance via classmethod vs staticmethod in Python?
@classmethodapproach creates an object of the right type if invoked on a subclass, rather than onDummyClassitself. If you know there will never be any subclasses, you might as well use@staticmethod.