Python Language Fundamentals: Object-Oriented Programming in Python
The Python language is one of the most popular in the world, and one of its most striking features is its robust support for object-oriented programming (OOP). OOP is a programming paradigm that uses objects and their interactions to design computer applications and programs. We will explore the fundamental concepts of OOP in Python in this chapter.
Classes and Objects
In Python, everything is an object, and each object is an instance of a class. Classes are like templates that define the characteristics (attributes) and behaviors (methods) that your objects will have. To create a class in Python, we use the 'class' keyword, followed by the class name.
class Car: pass
Above, we created an empty class called Car. Now, we can create objects of this class.
my_car = Car()
Now 'my_car' is an object of the Car class.
Attributes and Methods
Attributes are variables that belong to a class. They represent the characteristics of objects. Methods are functions that belong to a class, representing the behavior of objects.
class Car: color = 'red' # attribute def accelerate(self): # method print('Speeding up...')
We can access the attributes and methods of an object using dot notation.
my_car = Car() print(my_car.color) # prints 'red' my_car.accelerate() # prints 'Accelerating...'
__init__ constructor
The __init__ method is a special method that is called automatically when an object is created. It is used to initialize the attributes of an object.
class Car: def __init__(self, color): self.color = color def accelerate(self): print('Speeding up...')
Now when we create a Car object, we need to provide the color.
my_car = Car('blue') print(my_car.color) # prints 'blue'
Inheritance
Inheritance is an OOP feature that allows a class to inherit attributes and methods from another class. The class it inherits from is called a subclass, and the class it inherits from is called a superclass.
class Vehicle: def __init__(self, color): self.color = color def accelerate(self): print('Speeding up...') class Car(Vehicle): pass
Now, the Car class inherits from Vehicle and has all its attributes and methods.
my_car = Car('green') print(my_car.color) # prints 'green' my_car.accelerate() # prints 'Accelerating...'
These are the fundamental concepts of object-oriented programming in Python. OOP is a powerful tool for structuring your code in a clear and reusable way, and Python offers all the functionality needed to make the most of this paradigm.