This Python Class Methods lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
An ordinary method receives the object. A classmethod receives the class, and can build objects in a named way. A staticmethod receives neither.
Use a classmethod for an alternate constructor, such as building a course from a label.
Example 1: Start here
classmethod is for behaviour that belongs to the class. A normal method is for one object.
class Course: # a template for objects
def __init__(self, topic): # runs when you create the object
self.topic = topic # store this on the object
@classmethod # extra behavior for the next function
def python(cls): # define the function; it runs when you call it
return cls("Python") # send this value back to the caller
print(Course.python().topic)
Example 2: Instance method
An instance method receives the object as self.
class Course: # a template for objects
def __init__(self, title): # runs when you create the object
self.title = title # store this on the object
def show(self): # define the function; it runs when you call it
return self.title # send this value back to the caller
print(Course("Python").show())
Example 3: A class method
cls is the class, not one object. label can be called on the class itself.
class Course: # a template for objects
track = "Python" # text
@classmethod # extra behavior for the next function
def label(cls): # define the function; it runs when you call it
return cls.track # send this value back to the caller
print(Course.label())
Example 4: A static method
A static method does not need self or cls. It is just a function stored on the class.
class Course: # a template for objects
@staticmethod # extra behavior for the next function
def passed(score): # define the function; it runs when you call it
return score >= 80 # send this value back to the caller
print(Course.passed(82))
