As you can see above, we can have a “self-sufficient” data-type that contains both data and functionality that they can use to manipulate themselves.
Object oriented programming mimics real life
To understand object oriented programming, it is best to think of it as a way to mimic how we think about things in real life.
Method
An object in real life is something that “contains” lots of functionalities by itself. For example, a car is an object that can drive, park, and honk.
If we try to model above car in Python, we can do it like so:
class Car:def drive(self):print("Driving")# Do something to drive the cardef park(self):print("Parking")# Do something to park the cardef honk(self):print("Honking")# Do something to honk the car
For the usage is as simple like we’re using a function:
car = Car()car.drive()car.park()car.honk()
Attributes
In addition to having methods, objects also have attributes. Attributes are data that the object contains. For example, a car has a color, a model, and a year.
class Car:def__init__(self, color, model, year):self.color = colorself.model = modelself.year = year
To access the attributes, we can do it like so:
car = Car("red", "Toyota", 2019)print(car.color)print(car.model)print(car.year)
Term: Class and object
For now let’s take a step back and talk about some terminology.
Class
Class is a blueprint, it will define what kind of data and functionality an object will have.
class Car:def__init__(self, manufacturer, model, year):self.manufacturer = manufacturerself.model = modelself.year = yearself.speed =0def accelerate(self):self.speed +=5print(f"{self.manufacturer}{self.model} is accelerating. Current speed: {self.speed} mph")def brake(self):ifself.speed >0:self.speed -=5print(f"{self.manufacturer}{self.model} is braking. Current speed: {self.speed} mph")else:print(f"{self.manufacturer}{self.model} is already stationary.")
As you can see above, we have a class called Car. It has 3 data attributes (which is defined in __init__ method): manufacturer, model, and year. It also has 2 “functionalities” (which more commonly called methods): accelerate and brake.
Object
Object is a derived instance of a class, basically a class is a blueprint and an object is the actual thing that is built from the blueprint.
# Creating an object from `Car` classcar1 = Car("Toyota", "Camry", 2022)car2 = Car("Ford", "Mustang", 2023)# Using the objectscar1.accelerate()car2.accelerate()car1.brake()car2.brake()
init method
__init__ method is a special method that is called when an object is created. It is usually used to initialize the data attributes of the object.
You can see on above code that we are assigning three data attributes to the object: name, age, and level. name and age are assigned from the arguments that we passed when creating the object, while level is assigned with a default value of "Beginner".
self is a special keyword, that we’ll learn in just a bit.
Using instance methods
Instance methods are methods that are defined inside a class, and can be used by the object of that class.
class Person:def__init__(self, name, age):self.name = nameself.age = ageself.level ="Beginner"def greet(self):print(f"Hello, my name is {self.name}!")person = Person("Alice", 18)person.greet()
We’ve mentioned self keyword a couple of times now, but what is it? Basically self is a reference to the object itself. It is a special keyword that is used to access the “current” object’s attributes and methods.
Two objects created from the same class are independent
Two objects created from the same class are independent from each other. Mutating one object’s attribute will not affect the other object’s attribute.
# @title #### 04. Automobile Dealershipfrom rggrader import submit# In this assignment, you will implement classes in Python. # Here's the details of the task:# 1. Create a class named 'Car' having attributes 'manufacturer' and 'model'.# 2. The 'Car' class should have the following methods:# a. `display_info`: This should return a string "This car is a {manufacturer} {model}". The placeholders correspond to the 'manufacturer' and 'model' respectively.# b. `honk`: This should return a string "{manufacturer} says honk honk!". The placeholder corresponds to the 'manufacturer'.# c. `set_car_info`: This should be a method to set a new 'manufacturer' and 'model' for the car.# # The initial creation of a Car object should take the 'manufacturer' and 'model' as arguments.# Here is an example of what your code should emulate:my_car = Car("Toyota", "Corolla")answer = []answer.append(my_car.display_info()) # This should add "This car is a Toyota Corolla" to the 'answer' listanswer.append(my_car.honk()) # This should add "Toyota says honk honk!" to the 'answer' listmy_car.set_car_info("Ford", "Mustang")answer.append(my_car.display_info()) # This should add "This car is a Ford Mustang" to the 'answer' listanswer.append(my_car.honk()) # This should add "Ford says honk honk!" to the 'answer' list# Finally submit your answerassignment_id ="04-classes"question_id ="04_automobile_dealership"submit(student_id, name, assignment_id, str(answer), question_id)