Classes and Object-Oriented Programming (OOP)
Classes
Classes in Python allow you to create your own objects and data types. Functions should generally have something called an intialisation function (__init__
). This runs whenever you make a new instance of the class. You can also have a __str__
function to tell Python what to print when you use the print function on an instance of the class.
The self
parameter is the current instance. So for p1
, self
would be p1
and for p2
, self
would be p2
. You use it to save variables for later use. In the example above it’s letting us save name
and age
for later use. It may look like you need to provide self as a parameter, but it is already given when the function is called. You only need to provide the other parameters. You can use these variables in other functions by calling them through self
. This is show in the __str__
function with self.name
and self.age
.
Extending Programs with OOP
Inheritance
You can do a lot with Classes and OOP. For example, inheritance. Say you had a class called Animal. There are many kinds of animals: cats, dogs, horses etc. Some animals share features, like number of legs, but differ in other ways, like what sound they make. This is where inheritance comes in. You can have a parent class that encompasses all animals, and have child classes for specific animals. The child classes will inherit the functions and properties of the parent class, but you can add more specific functions and properties unique to the child. To declare a class as a child, you must put the parent class in the brackets next to the name of the child class. To use the __init__
function of the parent, you must call it using super()
.
Polymorphism
Polymorphism is another aspect of OOP. This is where you have the same function in multiple classes doing different things based on the class. Using our Animal example above, we can make an “animal noise” function which will return a different noise depending on the animal. Adding an “animal noise” function to each class will override the function in the parent class, and use the function in the child class instead.