Encapsulate state and operations
Model a domain concept with data and behavior.
Python · Const
The class statement defines a class object from a name, optional type parameters and bases, and an indented suite. A missing base list defaults to object; multiple bases enable multiple inheritance.
A class definition is an executable statement that creates a class object when its suite finishes normally. Its suite establishes the class namespace, and an optional parenthesized inheritance list selects base classes; without one, the class inherits from object.
class classname [type_params] [inheritance] : suiteA class object.
class Counter:
def __init__(self, start=0):
self.value = start
def increment(self):
self.value += 1
counter = Counter(2)
counter.increment()
print(counter.value)The class creates instances that store state and expose behavior through methods.
Model a domain concept with data and behavior.
Share or specialize behavior across related types.
Define reusable objects with a consistent interface.
The class statement defines a class object. It is executable, and its suite runs as part of the definition before the class object is produced.
Follow-up: What happens if there is no inheritance list? The class inherits from object by default.
The inheritance list appears in parentheses after the class name and normally contains base classes. Each item must evaluate to a class object that supports subclassing.
Follow-up: Can several bases be specified? Yes; listing multiple base classes enables multiple inheritance.
A class definition has the form class, a class name, optional type parameters, optional inheritance, a colon, and a suite. The class name is an identifier.
Follow-up: What is the simplest valid form? class Name: followed by an indented suite, such as pass.
objectdecoratorstype parametersinheritancemultiple inheritancemetaclasses