Classes And Objects

A class defines a type of object. An object is an instance of a class.

class Customer:
    pass
 
c1 = Customer()
c2 = Customer()

Attributes And Methods

Attributes store state. Methods define behavior.

class Customer:
    def set_name(self, new):
        self.name = new
 
    def identify(self):
        print("I am customer " + self.name)
 
cust = Customer()
cust.set_name("abc")
cust.identify()

self refers to the current object. Instance attributes are usually assigned through self.

Constructors

__init__() runs when a new object is created.

class Customer:
    def __init__(self, name):
        self.name = name
 
cust = Customer("abc")
print(cust.name)

Prefer defining required attributes in the constructor. Defining attributes in random methods makes object state harder to reason about.

Class Attributes

Class attributes belong to the class, not a single instance. They can be inherited by child classes and overwritten in subclasses.

Use the class name when changing class-level state. Changing class attributes through one instance can make code confusing.

Alternative Constructors

An alternative constructor is often written with @classmethod.

class BetterDate:
    @classmethod
    def from_str(cls, datestr):
        year, month, day = map(int, datestr.split("-"))
        return cls(year, month, day)

@classmethod receives the class as cls, so it can construct the current class or subclass.