9: Object Oriented Programming with Python#
Object-oriented programming is a paradigm, i.e. a way to write clear and simple programs. The principle is to model the elements of our program (like arrays and lists) as objects characterized by attributes and able to perform actions. These objects are built from classes that contain their construction plan.
In the Python language, almost everything is built to be an object: lists, dictionaries, numpy arrays, etc. For example when you write : list.append(), we are in fact using the append() method on a list object.
The Python, Numpy, Pandas, Matplotlib, Sklearn documentation is mostly made of classes that it is important to know how to decipher in order to learn new things thanks to the documentation.
Here is how to create classes simply and efficiently:
class vehicle:
"""
Here is an example of a "vehicle" class which contains the design plan
of "vehicle" objects
"""
# A class starts with an initialization function that contains the different attributes
def __init__(self, color='black', speed=0, wheels=4):
self.color = color
self.speed = speed
self.wheels = wheels
# here is a method "accelerer" which modifies an attribute of the object
def accelerate(self, speed):
self.speed += speed
# here is another method
def stop(self):
self.speed = 0
# here is a last method, very often used
def display(self):
print(f'color: {self.color}/wheels: {self.wheels}/speed: {self.speed}')
# creation of an object of the car class
car_1 = vehicle(color='red')
car_1.accelerate(100)
car_1.display()
color: red/wheels: 4/speed: 100
## Create subclasses
class electric_car(vehicle):
"""
The motorcycle class inherits the methods and attributes of the vehicle class
"""
def __init__(self, color='black', speed=0, wheels=4, autonomy=100):
super().__init__(color, speed, wheels) # super() allows to use the function of the "parent" class
self.autonomy = autonomy
# Re-writing of some methods
def accelerate(self, speed):
super().accelerate(speed)
self.autonomy -= 0.1 *self.speed
def display(self):
super().display()
print(f'autonomy: {self.autonomy}')
car_2 = electric_car()
car_2.display()
car_2.accelerate(10)
car_2.display()
color: black/wheels: 4/speed: 0
autonomy: 100
color: black/wheels: 4/speed: 10
autonomy: 99.0