Object-Oriented Programming

Object-Oriented Programming

Python is an object-oriented programming (OOP) language. In Python, just about everything is an “object”.

Objects have their own attributes. Let’s say we have an object called cat. A cat’s attributes could include color, size, and age. Suppose we want to know the color of the cat. We can inspect the color attribute like this:

cat.color 

red

Objects also have their own methods, which are basically built-in functions that are applied to the object. In this case, the cat’s methods could include jumping, sleeping, or playing. This is how we would ask the cat to jump:

cat.jump()

Now, you might be wondering: where did this cat object come from? How did we create it?

An object is an instance of a “class”, which can be thought of as a “blueprint” for creating objects. That means that our object, cat, came from a class. Let’s call the class Cat. The Cat class is where the attributes and methods are defined. It might look something like this:

class Cat:
    def __init__(self, name, color, age):
        self.name = name
        self.color = color 
        self.age = age
    
    def jump(self):
        print("jump!")

    def meow(self):
        print("meow!")

The cat object was created like this:

cat = Cat(name='Tabby', color='red', age=2)
cat.meow()
meow!

As we’ll learn very soon, all objects have a datatype. The datatype of an object is its class. In the case of our cat object, it’s datatype is Cat!

Note

When we start learning about dataframes in the next chapter, it’ll be helpful to remember 2 things:

  • a dataframe attribute looks like: dataframe.attribute_name (without parentheses)

  • a dataframe method looks like: dataframe.method() (with parentheses)

If this is super confusing, don’t worry! We will learn as we go.