What the hell is OOP
Python
Introduction to OOP in Python
In Python, object-oriented programming is a programming paradigm that uses “objects” to model elements of the real world. These objects can be concrete things like a car, a computer, or more abstract concepts like a bank account or a process.
Objects and Classes
Let’s imagine a simple object: a coffee cup. In OOP, the “class” is like the blueprint of the cup. It defines the characteristics (attributes) of the cup, such as its color, capacity, and material, as well as the actions (methods) it can perform, like being filled or emptied.
In Python, a class is defined like this:
class Cup:
def __init__(self, color, capacity):
self.color = color
self.capacity = capacity
def fill(self):
print("The cup is filled.")
def empty(self):
print("The cup is empty.")
Object Instances
Once the class is defined, we can create “instances” of this class. Each cup created from the Cup
class is an independent instance, having its own attributes.
my_cup = Cup("red", "300ml")
your_cup = Cup("blue", "250ml")
Here, my_cup
and your_cup
are two separate objects of the Cup
class.
Properties (Attributes)
The properties of the cup, defined in the class, are its attributes. In our example, color
and capacity
are attributes of the Cup
class.
Methods
Methods are functions defined in a class that describe the actions the object can perform. In our example, fill
and empty
are methods of the Cup
class.
Inheritance
Inheritance is another key concept in OOP. Suppose we have a ThermosCup
class that inherits from the Cup
class. The ThermosCup
will have all the properties and methods of Cup
, but it can also have additional properties and methods.
class ThermosCup(Cup):
def keep_hot(self):
print("This cup keeps the coffee hot.")
Collections of Objects
In Python, we can also have collections of objects. For example, if you have several cups, you could store them in a list. This allows interacting with multiple objects simultaneously.
Conclusion
In summary, object-oriented programming in Python allows structuring software as collections of objects with attributes and methods. Each object is an instance of a class, which acts as a blueprint. This approach to programming makes managing complexity in large software projects easier by making them more modular, reusable, and organized.
By using these concepts in Python, one can create efficient and well-organized programs that closely reflect the way we think and interact with the real world.