Skip to Content
Nextra 4.0 is released 🎉

Classes and Objects

Objects are a fundamental data structure in Python and programming in general. An object is a collection of related data and functionality. In Python, everything is an object, including numbers, strings, lists, and even functions.

Objects are are created using classes. You can think of a class as a blueprint for creating objects. A class defines the properties and behaviors that the objects created from it will have.

Creating Classes

You can create a class in Python using the class keyword.

When you use the class keyword you are creating a class definition

Here’s an example of a simple class that represents a Dog:

class Dog: species = "Canis familiaris" number_of_legs = 4

You have now defined a class named Dog with two class variables: species and number_of_legs.

Class Variables

Notice that the dog properties defined in the previous section ,species and number_of_legs, are the same for all dogs.

They make good candidates to be class variables because class variables are shared across all instances of a class.

AKA every dog will all have the same species and number_of_legs.

Creating an Object using a Class

Now you can use the class Dog to create an object (also called an instance) of that class. Basically, you can create a new “Dog” with the species (“Canis familiaris”) and number of legs (4) defined in the class:

my_dog = Dog()

The my_dog variable now represents a specific dog object with the species “Canis familiaris” and number of legs 4.

We can create as many objects as we want to using this class.

Object Methods

You can define functions (methods) inside a class to represent behaviors of the object. Methods are defined just like regular functions, but they are indented inside the class definition.

Here’s an example of adding a method to the Dog class:

class Dog: species = "Canis familiaris" number_of_legs = 4 def bark(): print("Woof!")

We added a bark method to the Dog class that returns the string “Woof!” when called.

Accessing Object Properties

An object’s properties are any variables and methods that are defined in the object’s class definition.

Now that we have created our dog objects, we can access their properties using the dot notation.

Dot notation is a way to access the properties and methods of an object using a dot (.) followed by the property or method name.

Here’s how we can access the properties of our dog objects:

print(dog1.name) # Output: Buddy print(dog1.age) # Output: 3 print(dog2.name) # Output: Max print(dog2.age) # Output: 5

We can also use the bark method we defined earlier in this same way with dot notation:

dog1.bark() # Output: Woof! dog2.bark() # Output: Woof!

Notice that when we call the bark method, we use parentheses () after the method name to indicate that we are calling a function.

Last updated on