Classes

Classes are a convenient way to group similar things together.

Recall that when we want to define a new function, we use the def keyword and write parameters, which will go inside the newly defined function. To call this function, we call it with parentheses and use arguments passed into the parameters.

def func(param1, param2):

We will be introducing a new keyword that you can use in order to define an object, class, which is analogous to making a new “template” for an object. All of the attributes of our new object will be nested inside of this class. Throughout this section, we will be referring to a specific example, how to create an object called Dog. Conventionally, classes are capitalized instead of functions, which are written in lowercase. For example, class Dog: vs def dog():

New Vocabulary

  1. Instance: What you call a singular “object” of a class.

    • a singular dog object is an instance of the Dog class

  2. Class attribute: An attribute that is shared by all instances of a class

    • all dogs have the same scientific name, “canis lupus familiaris”

  3. Instance attribute: An attribute that is specific to an instance of a class

    • not all dogs have the same fur color.

  4. Methods: functions inside of a class, that all instances of a class have access to and can call

    • all dogs can bark; this can be a method that prints out "woof woof!!"

The Dog Class

Below is the syntax for how to create a new class.

class Dog:
    scientific_name = "canis lupus familiaris"
    
    def __init__(self, name, age, fur_color):
        self.name = name
        self.age = age
        self.fur_color = fur_color
    
    def bark(self):
        print("woof woof!!")

Understand how each class represents an object that can have its own attributes and methods. In the next section, we will discuss the specific syntax of the code and what it represents.

Last updated