@classmethod() - Converts a method into a class method

The @classmethod decorator is most commonly used to instantiate a class by its name.  Instead of passing in self, the function gets an uninstantiated class object.  This is used commonly as a "factory pattern" to create and return the class instance, using a function that knows how to create class.  In the following example, we create two Student objects but from different sources.


class Student():
    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName

    def printName(self):
        print(f'First Name: {self.firstName}')
        print(f'Last Name: {self.lastName}')

    # Create an instance of student given their name.
    def fromName(cls, name):
        flName = name.split(' ');
        student = cls(flName[0], flName[1])
        return student

    # Create an instance of student given a record.
    def fromRecord(cls, record):
        student = cls(record["FirstName"], record["LastName"])
        return student

student = Student.fromName('Marc Clifton')

record = {
    "FirstName": "Cameron", 
    "LastName": "Pardo",
    "Year": "Freshman"

student = Student.fromRecord(record)


First Name: Marc
Last Name: Clifton
First Name: Cameron
Last Name: Pardo