This is an archived version of the course. Please see the latest version of the course.

Object-Oriented Programming in Python

You should have gotten the point by now that everything is an object in Python.

Here is a reminder of how to define a class and instantiate a class instance.

1
2
3
4
5
class Person:
    pass

person = Person()
print(type(person))

While the general OOP concepts are the same as in C++, there are many specific details in Python where things are implemented differently. Some of these requires a different way of thinking from what you have been exposed to in C++.

Firstly, if all you really need is a struct, then perhaps you should consider using a dict instead of a class?

Otherwise, below is an example class definition in Python, and how to use the class. Copy and paste the code into a text file, save it as person.py, and run it with python3 person.py to check out the output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Person:
    def __init__(self, firstname, lastname, age):
        self.firstname = firstname
        self.lastname = lastname
        self.age = age

    def greet(self, message):
        print(f"{self.firstname} {self.lastname} says {message}!")

    def get_fullname(self):
        return f"{self.firstname} {self.lastname}"

    def __str__(self):
        return f"A person named {self.get_fullname()} aged {self.age}"


person = Person("Josiah", "Wang", 20)  # What do you mean I don't look 20? :D
person.greet("I love Machine Learning!")
print(person.age)
print(person.get_fullname())
print(person)
print(type(person))
print(isinstance(person, Person))
print(isinstance(person, object))