• Python Snacks
  • Posts
  • Part 1: Mastering Object Oriented Programming: A Real Example

Part 1: Mastering Object Oriented Programming: A Real Example

In this multi-part series, I'm explaining the basics of object oriented programming (OOP) in Python.

This is part 1 of 3 a multi-part series about object oriented programming. If you want to skip ahead to the others:

At it’s foundation, object oriented programming is the core of the Python programming language. It’s a paradigm that organizes code around objects (instances of classes) that contain attributes and methods.

A while back, I put out an article explaining the differences between functions and methods. I’d suggest reading up on this if you’re not familiar with the difference between the two (spoiler alert: the difference is where the function is defined).

I think it’s easiest to start this multi-series off with a real-life example to show how objects can be represented in code.

An Example of an Object

Think of this as any kind of object around you, like that pen that’s sitting on your desk currently.

We can describe this pen using characteristics - the ink is red, it’s slim, and maybe it’s a ball point pen. We can say that these characteristics - things that are used to describe the object- are attributes.

We also know that the pen has different behaviors (or functionality) - it can click, write, or even run out of ink. We can say that these behaviors are the equivalent of a method in object oriented terms.

Object oriented programming: the code

We can represent this pen in code by using object oriented principals. If we were to generalize our pen from above, we know that the pen has a color, has a type of tip (ball point, for instance), and has a thickness associated with it. For additional fun, let’s add in the grip type (padded or plastic).

In addition, it can perform a number of different things. We identified it to click (to open/close it), write, and run out of ink.

In object oriented programming, we want our pen to be the name of our class (classes is how we define objects). Let’s suppose we only want to describe our pen. Maybe our class will look like this:

class Pen:
    def __init__(
        self, 
        color, 
        tip_type, 
        grip_type, 
        thickness = 3
    ):
        self.color = color
        self.tip_type = tip_type
        self.grip_type = grip_type
        self.thickness = thickness

# Example of creating a pen object,
#  which was described earlier.
desk_pen = Pen(
    color = 'red', 
    tip_type = 'ball point',
    grip_type = 'plastic'
)

Breaking this down, when we create the object in memory, it will run the __init__ method first. We’re passing in color, tip_type, and grip_type into this method. We can optionally pass in thickness, representing how large the pen is.

You may be wondering what self does. In our example, this says “this attribute is describing one specific pen”. When we go to create many pens, we want to make sure each of these attributes are tied to a specific pen. More on this in part 2 (3?).

However, we’ve only created the pen. The pen can’t do anything! If we were to add in some functionality to write, our class may look as such:

class Pen:
    def __init__(
        self, 
        color, 
        tip_type, 
        grip_type, 
        thickness = 3
    ):
        self.color = color
        self.tip_type = tip_type
        self.grip_type = grip_type
        self.thickness = thickness

    def write(self, itm):
        """Writes `itm` using our pen"""
        print(itm)

However, there’s an issue: the pen may run out of ink. We know each time we write with the pen, it uses ink, so we’ll need to keep track of this somehow or another. If we were to account for these:

class Pen:
    def __init__(
        self, 
        color, 
        tip_type, 
        grip_type, 
        thickness = 3
    ):
        self.color = color
        self.tip_type = tip_type
        self.grip_type = grip_type
        self.thickness = thickness

        # Ink level. Assume it's a fresh pen
        self.ink_level = 100

    def write(self, itm):
        """Writes `itm` using our pen"""
        self.check_ink()
        print(itm)
        self.ink_level -= 1

    def check_ink(self):
        if self.ink_level == 0:
             print('Refilling ink')
             self.ink_level = 100

Now, we can write as much as we want without ever having to worry about the ink levels dropping down.

Because we’ve been able to generalize what a pen looks like, we can create multiple different kinds of pens without having to write the code to define what the pen looks like and how it behaves:

# Create a pen
red_pen = Pen(
    color = 'red', 
    tip_type = 'ball point',
    grip_type = 'plastic'
)

# Create a different type of pen
blue_pen = Pen(
    color = 'blue', 
    tip_type = 'roller ball',
    grip_type = 'cushion'
)

Try it yourself: 2 Exercises

Take the object that’s immediately to your left (or other left if you’re directionality challenged) and see if you can make it into a Python object.

Then, see if you can figure this one out (hint: I took the object that’s to my left):

class MyObject:
     def __init__(self, **kwargs):
          self.game_name = kwargs.get('game_name')
          self.players_needed = kwargs.get('players_needed')
          self.is_unopened = kwargs.get('is_unopened', False)
          self.current_players = kwargs.get('current_players')
     
     def play(self):
          if self.current_players < players_needed:
              raise ValueError('Not enough players!')
          if not self.game_name:
              raise ValueError('What game?')
          if self.current_players == 0:
              raise ValueError('No players!')

     def open_game(self):
          if self.is_unopened:
               self.is_unopened = False

Next newsletter I’ll be talking about the concepts of object oriented programming and generalizing it to programming languages that aren’t Python-specific. Keep your eyes peeled for it.

Happy coding!

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate.