Defining Classes and Creating Instances
Explore how to define custom classes in Python to model real-world concepts. Learn the difference between classes and instances, how to assign attributes, and how methods use the self parameter to operate on individual objects. This lesson shows you how Python supports object-oriented programming by combining data and behavior.
We'll cover the following...
So far, we have worked exclusively with Python’s built-in objects. We know that an int handles arithmetic, a str represents text, and a list organizes sequences of values. However, real-world software often needs to model concepts that are more complex than any single built-in type can handle.
Many programs need to model domain-specific concepts that do not map cleanly to a single built-in type. For example, consider a flight simulator. A single primitive type, such as a number or list, does not represent a Spaceship. It has attributes such as a name, fuel level, and speed, along with defined behavior. For example, it may support operations such as acceleration, deceleration, and fuel consumption during flight. It should also prevent flight when the fuel level reaches zero.
This information could be represented using dictionaries and standalone functions, but that approach becomes difficult to manage and prone to misuse as programs grow. Object-oriented programming (OOP) allows developers to define custom types that combine data and behavior. Instead of relying only on built-in types, developers can define their own types to model program behavior.
The class keyword
A class is a blueprint. It defines the structure and behavior of an object, but it is not an object itself. Just as a blueprint for a house is not something you can live in, a class is a template used to create actual objects.
In Python, we define a class using the class keyword followed by the class name. By convention, Python class names use PascalCase (also known as CapWords), where every word is capitalized without underscores (e.g., Spaceship, UserProfile, GameLevel). This distinguishes them from functions and variables, which use snake_case. ...