1. python
  2. /basics
  3. /classes-objects

Python Classes and Objects

Introduction to Python Classes and Objects

Python's versatility extends to various domains such as web development, scientific computing, data analysis, and more.

Python and Machine Learning: A Perfect Match

The power of the language partially lies in its support for object-oriented programming (OOP). As developers, OOP enables us to build complex solutions that are modularly reusable, and generally easier to maintain.

In that sense, Python classes act as layouts, or templates for creating objects, which are instances of these classes. Understanding the inner workings of this aspect can be crucial to writing well-structured codebases.

We tailored this guide to give you a basic understanding of these concepts, while also providing some practical examples and caveats to keep in mind.

Defining Python Classes

To create a class, we'll be using the class keyword followed by a name and a colon. You'll probably notice the use of PascalCase, meaning that each word in the name starts with a capital letter. Within the class, we'll define various attributes and methods that the objects will contain.

class ClassName:
    # statement_body
class SimpleClass:
    test_variable = "Some placeholder text"

    def function(self):
        print("A message within the class.")

test_object = SimpleClass()

print(test_object.test_variable) # Output: Some placeholder text

test_object.function() # Output: A message within the class.

We'll go over the self parameter further on. For now, let's focus on what we have here. Note that the variable test_object now contains an object of the SimpleClass, which has a variable and a function defined in it. In this newly-created object, we can reach them by using the dot notation syntax.

To expand on this, we'll demonstrate a widely-used example with a simple class definition for a dog object, that approaches classes a bit differently.

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed
    def bark(self):

Within the class definition, we'll notice two attributes (name and breed) and a method (bark). We can leverage the __init__ method to initialize the object's attributes when a new object is created, and the self parameter to refer to its attributes and methods.

After we've defined the class, we can create objects of that very class. So, to produce a new Dog object, we could call the constructor like in the example below.

my_dog = Dog("Frea", "Golden Retriever")

Now, we have a new Dog object named my_dog, with the name attribute set to "Frea" and the breed attribute set to "Golden Retriever". We can also access the defined method, and well, make the dog bark.

my_dog.bark()  # Output: Woof!

Initializing Objects with Init

First off, we should understand that every object in Python has a type, defined by its class, and a set of attributes and methods, similar to what we saw in the examples. For instance, a string in Python is an object of the str class, containing attributes such as length and methods such as split and join.

mock_text = "A string"

print(type(mock_text))  # Output: <class 'str'>

Learn more about Strings in Python

As we previously saw, the __init__ method is a special way of initializing the object's attributes with values that are passed in as arguments to the constructor.

Also, the first parameter of every method in the class is always self, even though we don't explicitly pass in a value for it when we call the method.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def introduce(self):
        print(f"Hi, my name is {self.name} and I'm {self.age} years old.")

Let's illustrate this with a similar example.

Initially, we defined a class called Person with an __init__ method that takes two parameters (name and age) and sets the object's attributes accordingly. We can create a new object by calling the class constructor and passing in the required arguments.

person = Person("Guido van Rossum", 67)

Now, we have a new object, with the name attribute set to "Guido van Rossum" and the age attribute set to 67. Then, we can call the introduce method on this object to print out the message.

person.introduce()  # Output: Hi, my name is Guido van Rossum and I'm 67 years old.

Final Thoughts

We've explored the fundamentals that naturally lead to concepts such as inheritance, and several adjacent aspects which we'll cover in subsequent articles.

We strongly suggest that you jump into experimentation, and encourage you to modify what we provided here while observing the changes and behavior. But before you do that, remember to adhere to some established best practices.

One consideration is having meaningful names for the classes, attributes, and methods, so everyone involved can better follow your code. That includes avoiding single-letter variable names, keeping classes small and focused on a single responsibility, and writing comments explaining what the code does and why especially for complex or non-obvious sections.

Useful Resources

PEP 8 – Style Guide for Python Code

Offical Python Documentation on Classes

The Basics of Python Data Types

Variables in Python

The Basics of Python Functions