An Intro to Object-Oriented Programming
The proper way to program
In addition to relearning various aspects of programming foundations, I’d like to take an opportunity to write about Object-Oriented Programming (OOP). Object-Oriented Programming is a programming paradigm and a way to classify a programming language based on its features.
I’ll just by typing it as OOP from now on, for time's sake.
OOP is based on the concept of classes and objects, which contain the code and data that is structured into efficient, reusable blocks. This was a solution for old programmers who originally just wrote procedural programming, in long sequences of steps. This eventually became very messy as the programs got more and more complex. So they started breaking up the code into blocks or classes.
These classes are like frameworks or the structure for bundles of instance objects, methods, and attributes related to that class. An instance method is defined inside of a class and is a function associated, or bound, to an object. An instance method performs some actions for that particular object. An instance method is callable and can execute a block of code.
Python has a bunch of built-in classes and methods which you might be familiar with.
Let’s create an object.
string = "hey"
string is now a “str” object. Python has built-in methods for certain classes that we can call in order to perform certain tasks:
.upper() method just upper-cased our string. And
.title() just made the first letter capitalized.
What happens if we create an integer (int) object and try to perform that same method?
x = 5x.upper()#AttributeError: 'int' object has no attribute 'upper'
.upper() method doesn’t belong to the ‘int’ class, so we got this error! The
.upper() method belongs to the ‘str’ class, so only strings can inherit these methods.
Let’s create our own class now with a classic “dog” example. Usually, classes are given “camel” casing, which means every word begins with a capital letter. We’ll create a method for the class that only objects of this class can use.
Here we defined the “bark” function (which when is bound to an object, will be called a method). Now to use this class, it must be instantiated (with brackets) by assigning it to an object, like a dog’s name. Then we can call that bark method on our dog:
clifford = Dog()clifford.bark()#bark!
Our dog Clifford has now inherited the bark method.
We can also give methods of a class arguments, which require additional inputs to the brackets. Let’s define a method called “feed me” that takes in an amount of food, an integer, as an argument and prints a string telling us to feed hungry Clifford:
def feed_me(self, cups):
print("feed me", cups, "cups of food, human!")
Now let’s call the method on Clifford and pass in 3 as the argument:
clifford = Dog()clifford.feed_me(3)#feed me 3 cups of food, human!
Clifford is getting a little crazy now and speaking English.
What if we wanted to make another dog object in our Dog class?