Building more complex objects#

In the previous section, you were introduced to the syntactical properties of objects in Python, denoted as class. There is a lot that you can do with these outside of the overly simple car example. Let’s see what we can do.

Arguments and parameters in classes#

You can set default parameters in classes just like we did in the previous section or you can set them yourself with arguments. Let’s look at how to set this up by futher building upon the car example.

class Car:

    def __init__(self, make, model, year, color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color

    def drive(self):

        fast_cars = [ # list of fast cars to look through
            "porsche",
            "mercedes",
            "bmw",
            "ferrari", 
            "lamborghini",
            "audi",
            "corvette",
            "mustang"
        ]

        if self.make.lower() in fast_cars:
            print(f'Wow! You have a {self.make}. You can drive fast!')
        else:
            print(f'Let\'s just cruise.')
car = Car(make="BMW", model="M3", year="2023", color="black")
car.drive()
Wow! You have a BMW. You can drive fast!

In this example, we chose our car ourselves and populated self (i.e., the attributes/things that make up a class) based on the input for the parameters. Then, inside the method Car.drive(), I added a list of some cars that might be faster than others. When you call the drive, method, it looks through self.make and checks if it is one of the cars in the fast_cars list. Understanding self is arguably one of the most important components to understanding POOP.

Parent vs child#

No, you are not going to battle your parents. What this is denoting is a parent class versus a child class. Often times, there is a main or “parent” class that handles everything. There can also be a “child” class which might have additionally functionality but for practical reasons is split from the parent. Let’s look at this more.

class Parent:
    def __init__(self):
        self.parent_name = "Bob"

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.child_name = "Will"

parent = Parent()
print(f'The parent\'s name is {parent.parent_name}.')
child = Child()
print(f'The child\'s name is {child.parent_name}.')
The parent's name is Bob.
The child's name is Bob.

As you can see, the child class is able to access the attribute parent_name. This is called class inheritance. This is done using super().__init__(). When including this line of code you are bringing the attributes from a parent class. To denote which specific class, we provide Child(Parent) so that the child class knows which parent class to pull from.

More complex stuff#

Let’s take a look at another more complex way of building and working with objects: I want to create an object that handles my data. I have participants take a multiple choice test on their knowledge of one of my favorite artists, Karen Carpenter. There are right answers and wrong answers. Let’s build a class that takes their answers, and calculate their scores.

class KCtest:
    def __init__(self, data):
        self.answer_key = ["A", "B", "B", "D", "A", "C", "A", "D", "A", "C"] # here are the correct answers
        self.data = data # assign data to class
        
        # check if sc
    def score(self):
        """Function that scores data"""
        scores = 0 # empty list to store points
        for i in range(len(self.data)):
            if self.data[i] == self.answer_key[i]:
                scores += 1
            else:
                scores += 0

        # calculate score
        score = scores/float(len(self.answer_key)) * 100

        # add to self and return
        self.score = score

        # print score
        print(f'This student scored %.2f on the test examining their knowldege of Karen Carpenter.' % self.score)

In the above cell, I have created a class called KCtest. It takes the data from a participant and scores it. Let’s see this in action.

student_answers = ["A", "A", "B", "D", "D", "C", "A", "D", "B", "C"]
KCscore = KCtest(data=student_answers)

In the above cell, I have someones data and I put it into the class.

KCscore.score()
This student scored 70.00 on the test examining their knowldege of Karen Carpenter.

In the above cell, I execute the method .score(). Remember: methods require parentheses when calling them!

Closing remarks#

Try finding an instance of code or issue that you have encountered in which you solved it with code and re-implement it with object-oriented programming. The logic!

Although these examples and overall tutorial is relatively simple, its soft introduction to POOP should provide you with at least the confidence to tackle it at a greater scale in the future! Lot’s of packages and software make use of POOP so being familiar with it, the terms involved and how to build your own OOP code is imperative!