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.
Syntax overview for class declaration and definition:
class <class_name>:
<attribute_name> : <attribute_type>
<attribute_name> : <attribute_type> = <attribute_default_value>
def __init__(self, <parameter_name> : <parameter_type>):
self.<attribute_name> = <parameter_name>
def <method_name>(self, <parameters...>) -> <return_type>:
<method_body>
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)
~~~
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”) ~~~
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:
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:
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.
student1: TarHeel = TarHeel()
student1.name = "Claire"
student1.PID = "123456789"
student1: TarHeel = TarHeel()
student1.name = "Aneka"
student1.PID = "987654321"
Now if we were to run the following:
It would output: