I have never used @classmethod and I do not think of any examples to use it, I know how it works but I do not know when it's time to use it for example
class Example:
def __init__(self,param1,param2):
self.param1 = param1
self.param2 = param2
@classmethod
def my_method(cls,param1,param2):
return cls(param1,param2)
example = Example.my_method(1,2)
print(example)
output:
<__main__.Example object at 0x02EC57D0>
But why not do this?
class Example:
def __init__(self,param1,param2):
self.param1 = param1
self.param2 = param2
def my_method(self,param1,param2):
return Example(param1,param2)
example = Example(1,2)
method = example.my_method(3,4)
print(method)
output:
<__main__.Example object at 0x02EC57D0>
It's the same result but it does not come to mind when I could use classmethod
Example
instance instead of one from your subclass. – Laciniate__init__
did something like open a network connection or consume some sort of resource; you wouldn't want to create an instance just to create other instances. You could just callExample.my_method()
without having any actual Example instances. Also this question might be helpful #38738 – Matheson