Class & Object
Learn how to create blueprints (classes) and instances (objects) in Python.
Concept
Class | Object |
---|---|
A blueprint or template for creating objects | An instance of a class |
Defines attributes (data) and behaviours (method) that the created objects will have | Contains data and methods defined by the class or has its own set of attribute values |
Uses the class keyword | Created using the class name followed by parentheses |
Contains the __init__ method for initialization | Created by calling the class like a function |
Implementation
Let's explore how to create classes and objects in Python.
Create a Class
To create a class in Python, use the class
keyword followed by the class name. By convention, class names are written in CamelCase.
Car
is your blueprint for creating car objects. It defines the attributes and methods that each car object will have.
__init__()
method: This is the constructor that initializes the instance attributes when a new object is created. It takesself
(the instance itself) and other parameters to set the initial state of the object.- Attributes created in
__init__()
are called instance attributes and are unique to each object.
- Attributes created in
Create an Object
Cohesion and Coupling
Understand the concepts of cohesion and coupling in Python OOP, and how they affect code maintainability and design.
Encapsulation
Understand how to use encapsulation in Python to bundle data and methods into a single unit (class) and restrict direct access to some of the object's components.