Object Oriented Programming


Overview

A class is a blueprint for an object. An object’s class is what defines its properties and capabilities. Classes are made up of 3 main parts; properties, constructors and methods.

Definition Syntax

Syntax overview for class declaration and definition:

Example of class declaration: ~~~ {.python} class Animal: sound: str

def __init__(self, noise: str):
    self.sound = noise

def make_noise(self, times: int) -> None:
    for _ in range(times):
        print(self.sound)

~~~

Creation Syntax

Initializing a composite data type requires constructing a new object. The general syntax for this is as follows:

Example of object creation: ~~~ {.python} pig: Animal = Animal(“oink”) dog: Animal = Animal(“woof”) ~~~

Properties

Classes have properties. Each object made from a class will have all the properties established in that class. Additionally, each property in a class has a specific type. So, all objects we create from a certain class will contain all properties defined in the class, and we can customize the values within these properties for each individual object. For example:

The properties declared inside the body of the TarHeel class are name, PID, and hatesDook. Every TarHeel object we make will have these properties.

In this example, there are defualt values for each property of "", 0, true respectively. We can declare two new Tar Heels with all the default properties as seen below:

Property Access

To access an object’s property, just use the name of the object followed by the dot operator (.) followed by the property name.

For instance the code above accesses first the PID property of student1 and then the hatesDook property of student2. We would expect this to print:

Property Assignment

We can also use the dot operator (.) in order to reassign properties of objects. Notice we have to specify which student we are referring to.

Now if we were to run the following:

It would output: