Contents

Python Classes: A Beginner's Guide

Learn the basics of Python classes, including how to create, define, and use them.

Website Visitors:

Classes are an integral part of object-oriented programming (OOP) in Python. They provide a blueprint or template for creating objects, which are instances of a class. Understanding classes and their associated concepts, such as __init__, self, and more, is crucial for building modular and reusable code. In this article, we’ll delve into the details of classes in Python, explaining each concept along with examples.

Before we learn what is a class, lets look at what is an Object in Python.

Object

In Python, an object is an instance of a class. It is a fundamental concept in object-oriented programming (OOP). Objects are created from classes and can have their own unique states (attributes) and behaviors (methods).

When an object is created, it inherits the attributes and methods defined in its class. These attributes represent the object’s data, while methods represent its behaviors or actions that can be performed. Each object of a class can have different attribute values, allowing individual instances to have their own state.

For example, consider a class named Person:

1
2
3
4
5
6
7
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name}. I am {self.age} years old.")

In the above code, Person is a class that has the attributes name and age, as well as the greet method. An object (instance) of this class can be created as follows:

1
2
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

Here, person1 and person2 are two distinct objects of the Person class. They have their own unique values for the name and age attributes. We can call the greet method on these objects:

1
2
person1.greet()  # Output: Hello, my name is Alice. I am 25 years old.
person2.greet()  # Output: Hello, my name is Bob. I am 30 years old.

Each object maintains its own state and can perform actions (methods) defined in the class. In Python, an object is an instance of a class that encapsulates its own set of attributes and behaviors. Objects allow us to create multiple instances with different states, enabling code reusability and modularity.

In the print statement f is mandatory. This is called F-strings. Check out Python Strings article for more information.

Introduction to Classes

A class is a user-defined data type that encapsulates data (attributes) and functions (methods) into a single entity. It represents a blueprint or a prototype for creating objects. Objects are instances of a class and can have their own unique states and behaviors.

A class in Python is a blueprint for creating objects. It defines the properties and behaviors that objects of that class will have. Think of a class as a template or a cookie cutter, and objects as the cookies that are created using that template. Each object created from a class is called an instance of that class.

Creating a Class

In Python, you can define a class using the class keyword followed by the class name. Here’s a simple example:

1
2
class Person:
    pass

In the above code, we defined a class named Person with no attributes or methods. The pass statement is a placeholder that allows the class to be defined without any content.

Example:

To create a class in Python, you use the class keyword followed by the class name. Here’s an example of a simple class in Python:

1
2
3
4
5
6
7
8
class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def display_info(self):
        print(f"{self.year} {self.make} {self.model}")

In the example above, we define a Car class with attributes make, model, and year. The __init__ method is a special method called a constructor, which is used to initialize the object’s attributes. The display_info method is a simple method that prints out information about the car.

Adding Attributes

Attributes are variables that store data associated with a class or an object. They can be defined within the class using the self keyword. The self parameter refers to the instance of the class and is used to access its attributes and methods. Let’s add some attributes to the Person class:

1
2
3
4
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

In the above code, we defined an __init__ method. This special method is called a constructor and is executed automatically when an object of the class is created. The self parameter is required and refers to the instance of the class. It is used to assign values to the attributes name and age.

self Explained

self is a reference to the current instance of the class, and is used to access variables that belong to the class.

When a method is called, Python passes the instance object (usually named self) as the first argument. This allows methods to access and modify attributes of the class. Any variable assigned to self becomes an instance variable. It can only be accessed through a class instance, rather than through the class itself.

For example:

1
2
3
4
5
6
7
8
9
class Person:
  def __init__(self, name):
    self.name = name

  def say_hi(self):
    print(f"Hello, my name is {self.name}!")

p1 = Person("John")
p1.say_hi()

Here:

  • self refers to the instance p1 when say_hi() is called.

  • name is assigned to self, making it an instance variable that can only be accessed through p1 (e.g. p1.name)

  • self.name prints the name attribute of the current instance

  • Without self, there would be no way to access instance variables from methods. It provides a reference to the current object.

  • self is not a special keyword, but a reference like any other. It just happens to always refer to the current instance by convention.

So in summary, self represents the instance of the class, and allows methods to access and modify attributes of that specific instance.

__init__ Explained

The init() method in Python is a special method that is automatically called when an object is instantiated from a class. It is used to initialize the attributes of newly created objects of a class.

Some key things to know about the init() method:

  • init() is called automatically whenever a new instance of a class is created. It allows the class to initialize attributes of the newly created object.

  • It must have at least one argument, conventionally named self, that refers to the instance being created.

  • Any other arguments passed during object instantiation are also passed to init(). These arguments can then be used to set attributes of self.

  • init() is intended to perform any initialization tasks that are required for the object to work properly. This includes assigning values to attributes, opening files/connections etc.

Example:

1
2
3
4
5
6
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

Here:

  • init() takes name and age as arguments and assigns them to attributes of self.
  • When an instance p1 is created, name and age values are passed to init() and used to initialize p1.

So in summary:

  • init() allows initializing attributes when a new instance is created.
  • It is called automatically at object creation.
  • Any arguments passed during instantiation are passed to init().
  • It performs any setup work required for the object to function properly.

Attributes and Objects

Here are the key things to know about attributes and methods in Python class definitions:

Attributes:

  • Attributes are variables that belong to a class and its objects.
  • Attributes are defined inside the class but outside any methods with just a name and optional value.
  • Attributes can be accessed via self inside methods or directly from an instance outside methods.

Methods:

  • Methods are functions defined inside a class. They act on instances of the class.
  • Methods take self as the first argument which refers to the current instance of the class.
  • self allows methods to access and modify attributes of the current object.

Example class definition:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Person:

  # Attributes
  name = "" 
  age = 0

  # Method
  def set_name(self, name):
    self.name = name

  # Method  
  def greet(self):
    print(f"Hello, I am {self.name}!")

# Usage
person1 = Person()
person1.set_name("John") 
person1.greet()

Breakdown:

  • name and age are attributes
  • set_name() and greet() are methods
  • set_name() uses self to set the name attribute
  • greet() uses self to access and print the name attribute

So in summary:

  • Attributes store data belonging to each instance
  • Methods contain reusable code acting on the instance
  • self provides access to attributes from within methods

Creating Objects

To create an object of a class, you simply call the class as if it were a function, passing any required arguments. Here’s an example of creating two Person objects:

1
2
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

In the above code, we created two objects person1 and person2 of the Person class, passing the name and age values as arguments.

Accessing Attributes

Once objects are created, you can access their attributes using the dot notation. Here’s an example:

1
2
print(person1.name)  # Output: Alice
print(person2.age)   # Output: 30

In the above code, we accessed the name attribute of person1 and the age attribute of person2.

Adding Methods

Methods are functions defined within a class. They can perform operations on the class’s attributes or modify the state of the object. Here’s an example of adding a method to the Person class:

1
2
3
4
5
6
7
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name}. I am {self.age} years old.")

In the above code, we added a method called greet to the Person class. This method prints a greeting message using the name and age attributes of the instance.

Calling Methods

To call a method on an object, you use the dot notation similar to accessing attributes. Here’s an example:

1
2
person1.greet()  # Output: Hello, my name is Alice. I am 25 years old.
person2.greet()  # Output: Hello, my name is Bob. I am 30 years old.

In the above code, we called the greet method on both person1 and person2.

Class Variables

Class variables are shared among all instances of a class. They are defined within the class but outside any method. Here’s an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Person:
    species = "Human"  # Class variable

    def __init__(self, name):
        self.name = name

person1 = Person("Alice")
person2 = Person("Bob")

print(person1.species)  # Output: Human
print(person2.species)  # Output: Human

In the above code, species is a class variable that is shared by all instances of the Person class. Changes to the class variable affect all instances.

Inheritance in Classes

One of the key features of object-oriented programming is inheritance. In Python, you can create a new class that inherits from an existing class. The new class is called a subclass, and the existing class is called a superclass. The subclass inherits all the attributes and methods of the superclass and can also define its own attributes and methods.

1
2
3
4
5
6
7
class ElectricCar(Car):
    def __init__(self, make, model, year, battery_size):
        super().__init__(make, model, year)
        self.battery_size = battery_size

    def display_battery_info(self):
        print(f"Battery size: {self.battery_size} kWh")

In the example above, we define a ElectricCar class that inherits from the Car class. The __init__ method of the ElectricCar class calls the __init__ method of the Car class using super(), and then initializes its own attribute battery_size. It also defines a new method display_battery_info to display information about the battery size.

Conclusion

Classes in Python provide a powerful mechanism for creating objects with their own attributes and behaviors. By understanding concepts like __init__, self, attributes, methods, and class variables, you can build modular and reusable code. Classes are fundamental to object-oriented programming and are widely used in various Python applications.

This article has provided a detailed overview of classes in Python, explaining each concept along with examples. Armed with this knowledge, you can start building your own classes and objects in Python, enabling you to write more organized and maintainable code.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.