I tried to find out the difference between 1) @classmethod and 2) invoking the class inside a method. But, they output the same result and their execution time's pretty much identical. Here is the code:
import time
class Student(object):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@classmethod
def from_string(cls, name_str):
first_name, last_name = map(str, name_str.split(' '))
student = cls(first_name, last_name)
return student
def from_string2(name_str):
first_name, last_name = map(str, name_str.split(' '))
student = Student(first_name, last_name)
return student
st = time.time()
scott = Student.from_string('Scott Robinson')
et = time.time()
print(f'{et-st:.8f}')
st = time.time()
scott2 = Student.from_string2('Scott Robinson')
et = time.time()
print(f'{et-st:.8f}')
Output>>> 0.00004053
Output>>> 0.00003552
I'm curious why @classmethod is preferred to invoking the class inside a method? Please enlighten me.