Pillars of Object Oriented Programming (in Python)

https://pixabay.com/photos/lens-camera-lens-focus-focusing-1209823/

Abstraction

https://pixabay.com/photos/monkey-zoo-animal-world-observing-2195107/
class Animal(object):

def __init__(self, name):
self.name = name
self.size = None
self.species = None
self.food_type = None
self.color = None

def make_noise(self):
return("Roaaaaaaaaar!")

Encapsulation

Encapsulation is the second pillar of OOP we’ll look at. The concept of Encapsulation is one of information hiding, where you might want some sensitive information or redundant information to remain private except on a need-to-know basis. Some programming languages have keywords to explicitly state if some information is public or private but Python is not one of those languages. There is a convention in Python that a variable whose name is prefixed by an underscore should be considered private (called Name Mangling). Let’s use our zoo example to showcase this by changing the defined color of an animal.

class Animal(object):

def __init__(self, name):
self.name = name
self.size = None
self.species = None
self.food_type = None
self._color = None

def color(self):
return(f"This animal is {self._color}")
tiger = Animal("Tony")
tiger._color = 'Orange'
tiger.color()

Inheritance

https://pixabay.com/photos/animal-tiger-big-cat-safari-1868911/
class Animal(object):

def __init__(self):
self.size = None
self.species = None
self.food_type = None
self.color = None

def make_noise(self):
return("Roaaaaaaaaar!")

class Tiger(Animal):

def __init__(self):
super().__init__()
self.species = "Panthera tigris"
self.size = "Large"
self.food_type = "Carnivore"
self.color = "Orange"
Tony = Tiger()
Tony.make_noise()

Polymorphism

https://pixabay.com/photos/snake-green-macro-animal-zoo-1634293/
class Snake(Animal):

def __init__(self):
super().__init__()
self.size = "Medium"
self.food_type = 'Carnivore'

def make_noise(self):
return("SSSSsssss!")

Concluding Remarks

There it is, a brief summary of Object Oriented Programming and the Four Pillars that define it. I hope this post was helpful to those wanting to take an initial look at OOP. Best of luck!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store