Quick & easy; Object-oriented Programming from the ground up with Examples from Pikachu and Bay Area Rapid Transit (BART)

Winston Robson
May 16 · 4 min read

What is Object-oriented Programming?

Object-oriented Programming (OOP), is a programming paradigm which provides a means of structuring programs so that properties and behaviors are bundled together as individual objects. These objects contain data, in the form of fields (attributes), and code, in the form of procedures (methods).

Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms.

Classes vs Objects (Instances)

When executing OOP with Python, each object is an instance of some class.

Think of a class as a blueprint for how an object may operate. The object is a particular instance derived from the class.

For example, an object could represent a particular person with attributes including name, age, address, etc., and methods like walking, talking, breathing, and running. The class would cover people in general.

Modified from The Code Ninja, check out their OOP article here

How to OOP in Python?

To kick off with Object-oriented Programming in Python, one first needs to construct a class.

Classes

Starting a class is as simple as class ThisIsAClass():.

Unlike a function, where one starts with def, writes in lowercase, and needs to end off with parentheses (e.g. def this_is_not_a_class():), a class utilizes capitalization and may or may not make use of parentheses.

I.e. classes can also be started like:

class ThisIsAClass:

class ThisIsAClass(object):

Attributes

From there, the next step is to initiate the class with an __init__() function. This is how attributes will be set, and brings in the self that is the object. It will look something like;

def __init__(self, name, object_type, health):    self.name = name
self.ot = object_type
self.health = health

Because the program is focused on the object (self), all attributes are set with respect to self, and will be called for use by methods as represented with the self (object).

Methods

Defined inside a class, methods are used to get the contents of an instance. Methods can also be used to perform operations with the attributes of an object.

It is critical to remember that all code is oriented to the object, so, as seen in __init__ , the first argument will always be self;

def dodge(self, ability, attack_strength):
# likelihood of success
odds = ability / 100
# accuracy of opponent
outcome = random.randint(0,1)

# successful dodge
if odds >= outcome:
print(f'{self.name} has successfully dodged')

# unsuccessful dodge
else:
print(f'{self.name} failed to dodge')
# calculate new health
self.health -= attack_strength

Note: other arguments introduced do not need to be self oriented.

Let’s Code an Example

For this illustration, let’s say we are in Antioch, California and need to get to San Francisco International Airport (SFO) for a flight.

The plan is to take Bay Area Rapid Transit (BART) — a “rapid transit” (ha ha) public train system serving the San Francisco Bay Area — from the Antioch station to the SFO station.

Class & __init__(self)

As we have a specific route, Antioch to SFO, the example class will only cover that specific route, but I challenge you to fork the repo and expand the class to encompass all of BART after we’re done here!

The attributes of our class include:

stops > the number of stops the train will go through

stop_number > the stop (by number) where the train starts out

reverse > if the train is going from Antioch to SFO (reverse=False) or from SFO to Antioch (reverse=True)

For the sake of simplicity, the train will always start at the Antioch station, the 0th station, and will be moving towards the SFO station. This means we will only need to argue self and stops in __init__ and can start out with;

The Movement Method

Next we need to define a method for how the train will move from one stop to the next, which can kick off like;

def to_the_next_stop(self):

Then adding in checks for the beginning and end of the line, switching self.reverse from True to False or vice versa like;

        if self.stop_number + 1 == len(self.stops):
self.reverse = True
if self.stop_number == 0:
self.reverse = False

And wrapping up with actually moving the train from the current stop to the next stop, not forgetting to count down when reversing, similar to;

        if self.reverse == False:
self.stop_number += 1
if self.reverse == True:
self.stop_number -= 1

Finally, call a print() to update us as to what is going on, include time for passengers to enter/exit, and the method should come out along the lines of;

Wrap up & Run

Code out the following at the bottom of your script and you’re ready to take your trip;

Here’s what running the script in Terminal looks like:

Congratulations, you did it! If you enjoyed this story please don’t forget to follow & “clap”, drop a comment with any questions or letting me know what you’d like to see next and I’ll get back to you ASAP. Here’s the full script.

If you’d like to challenge yourself, and further explore OOP, fork this Story’s repository on GitHub (link) and expand the class to include all BART lines; leave a response with a link to your repo and I’ll gladly check it out.

For a more in depth example of Object-oriented Programming in Python, checkout “LinkedOut” where, in just 10 minutes, you will code up a Bot that posts to LinkedIn for you. Technology is cool.

Thanks for reading, have a great day!

Future Vision

A publication centered around high quality storytelling

Winston Robson

Written by

Terrible in onset. Swift in execution. winstonrobson.com

Future Vision

A publication centered around high quality storytelling

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade