OOP1
OOP1
relies on objects. These objects can have attributes and methods. While
attributes store data, methods define behavior.
Like many other programming languages, Python supports both OOP and
functional programming. However, OOP becomes valuable when writing
large-sized and complex programs.
In this article, you will learn the benefits of OOP in Python, how to define a
class, class and instance attributes, and instance methods. You will also
learn the concept of encapsulation and how to implement inheritance
between classes in Python.
To fully understand this article, you should have the following prerequisites:
speaker_one = Speaker()
print(speaker_one)
In the preceding code, you defined a class named Speaker without any
attributes or methods. You used the keyword pass in the class body. In
Python, the pass keyword does nothing and is usually used as a
placeholder.
In line four of the code, you created an instance of the Speaker class and
assigned it to the variable speaker_one. This process is also known as
instantiating an object from a class. You then printed speaker_one in line
five.
Now run the code by running the command python classes.py in your
terminal. You will get an output similar to this in your terminal:
<__main__.Speaker object at 0x10087f8e0>
The output shows that speaker_one is an object. 0x10087f8e0 in the
output shows the memory address where Python stores the object on your
computer.
The memory address in your terminal output will be different.
You can create several more instances from the Speaker class and they
will all be different from one another. To verify this, let’s use the equality
comparison (==) operator. In your classes.py file,
delete print(speaker_one) and add the following to the bottom of your
code:
speaker_two = Speaker()
if speaker_one == speaker_two:
print("speaker one is the same as speaker two")
else:
print("speaker one is different from speaker two")
Now run python classes.py in your terminal. You will get the following
output:
speaker one is different from speaker two
Class and Instance Attributes
In this section, you'll add attributes to your Speaker class. You can see
attributes as data stored within an object. While class attributes are
common to all instances created from your class, instance attributes are
unique to each instance.
Now modify your classes.py file by replacing your code with the
following:
class Speaker:
brand = "Beatpill" # class attribute
class Speaker:
brand = "Beatpill"
def power_on(self):
print(f"Powering on {self.color} {self.model} speaker.")
def power_off(self):
print(f"Powering off {self.color} {self.model} speaker.")
speaker_one.power_on()
speaker_two.power_off()
Now run python classes.py in your terminal and you will get the
following output:
Powering on black 85XB5 speaker.
Powering off red Y8F33 speaker.
Encapsulation in Python
Encapsulation is one of the core concepts of OOP. It refers to the bundling
of data (attributes) and methods within a class. Encapsulation provides
data protection and control over how the code interacts with an object's
internal state.
class Speaker:
brand = "Beatpill"
def power_on(self):
print(f"Powering on {self._color} {self._model} speaker.")
def power_off(self):
print(f"Powering off {self._color} {self._model} speaker.")
def get_color(self):
return self._color
Inheritance in Python
Inheritance is another core concept of OOP. It allows classes to inherit
attributes and methods from other classes. The new class inherits
attributes and methods from the existing class, known as the parent or
base class. The new class is called the child or derived class.
Inheritance promotes code reuse by allowing the child class to inherit and
extend the functionality of the parent class. This helps in creating
hierarchical relationships between classes and organizing code in a more
structured and logical manner.
class DerivedClass(BaseClass):
# Derived class methods and attributes
To see how inheritance works, modify your code as follows:
class Speaker:
brand = "Beatpill"
def power_on(self):
print(f"Powering on {self._color} {self._model} speaker.")
def power_off(self):
print(f"Powering off {self._color} {self._model} speaker.")
# Add a SmartSpeaker class and make it inherit from the Speaker class
class SmartSpeaker(Speaker):
def __init__(self, color, model, voice_assistant):
super().__init__(color, model)
self._voice_assistant = voice_assistant
def say_hello(self):
print(f"Hello, I am {self._voice_assistant}")
Applying the lessons covered in this article will help you improve your
Python programming experience and increase the efficiency and
maintainability of your code.