Python Object Oriented Programming (OOP)
kster
Posted on September 29, 2022
Object Oriented Programming is the process of defining classes and creating objects to represent the responsibilities of a program.
The way you go about creating an object from a class is similar how you would create a home from a blue print. When an object is created, your program asks the operating system for resources, namely memory, to be able to construct the object. On the other hand, when a house is made from a blue print, the contractor will ask what kind of wood, windows, and doors will be use in order to build the home.
Instantiation - breathes 💨 life into a class
When creating an object from a class you will need to instantiate (create) it. What this is doing is asking the operating system to give enough memory to create an object.
To instantiate an object, you add the name of the class followed by parentheses.
class House:
house = House()
- 'house' is the variable that holds you object's instance.
- 'House()' is the instantiated object.
Adding attributes to a class
To add attributes to a class you will need to tell the class what attributes it should have at construction time, when an object in instantiated. This is done by a function called a 'constructor' that is used at the moment of creation.
Constructor
In Python, the constructor has the name __init__
The __init__
method lets the class initialize the object's attributes. ( This is only used within classes )
You will need to pass a special parameter self
to the constructor. (self
refers to the objects instance this binds the objects attributes to the arguments received). Any assignment to this keywork ends up on the object instance.
class Car:
def __init__(self):
self.make = "Audi"
self.model = "A4"
car = Car()
print(car.make)
print(car.model)
print("Is your car make", car.make, "and model", car.model)
This example shows a class Car
with two attributes, the make
and model
, are assigned to the constructor __init__()
.
Posted on September 29, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.