Class & Object¶
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.
Step 1: 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.
classDiagram
class Car {
+int wheels = 4
+str brand
+str model
+int year
+bool is_running
+start()
+stop()
}
-
__init__()
method: This is the constructor that initializes the instance attributes when a new object is created. It takes self
(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.
Step 2: Create an Object¶
classDiagram
class Car {
+int wheels = 4
+str brand
+str model
+int year
+bool is_running
+start()
+stop()
}
Car <|-- my_car : instance
Car <|-- another_car : instance