Classes

Classes in Python

In Python, classes are a fundamental part of OOP. They let you create custom data types that combine data (attributes) and functions (methods) into reusable blueprints for your program.

Essentially, a class is a blueprint for a data type, letting you invent your own types and bundle the data and behaviour into a single, reusable structure. For example, you could make a class called Dog, and every individual dog in your program would be created using that template.

class Dog:
    """A simple class to represent a dog."""
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print(self.name.title() + " is now sitting.")

Best Practices

  • Use CamelCase for class names (e.g., Dog, UserProfile)
  • Start with a capital letter
  • Include a docstring below the class definition to describe its purpose
class Car:
    """Docstring example: A class to represent a car."""
    ...

Class Layout

The __init__() method is a special method that is called only when a new object is created. It has the arguments of self and then all the properties included in the Class.

class ClassName:
    def __init__(self, name, age):
        self.name = name
        self.age = age
  • self refers to the instance itself
  • name and age are parameters passed when the class is instantiated
  • self.name and self.age are the instance's attributes

A method is a function inside a class that operates on its data. It can be called on a created instance by using the syntax instance.method().

def sit(self):
    print(f"{self.name.title()} is now sitting.")

my_dog.sit()

Instantiation

Instantiation is the process of creating an instance (object) from a class. The following creates a specific Dog object with a name and an age using the dog class from the "Classes in Python" section.

my_dog = Dog("Buddy", 4)

Updating Instances

You can update an attribute of an instance in two ways. Either directly accessing the attribute using the syntax of instance.attribute and reassigning it or via a setter method that is defined inside the class.

# directly
my_dog.name = "Max"

# setter method
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Setter method to update the age
    def set_age(self, new_age):
        self.age = new_age

my_dog.rename("Max")

Getter and Setter

Getter methods are functions defined inside a class to return values.

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

    # Setter method to update the age
    def set_age(self, new_age):
        self.age = new_age

# Getter method to return value
def get_name(self):
    return self.name

The __str__() Method

Use the __str__() method in your class to define how your object will be represented as a string, like when passed to print().

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

    # Setter method to update the age
    def set_age(self, new_age):
        self.age = new_age

    # Getter method to return value
    def get_name(self):
        return self.name

    def __str__(self):
        return f"{self.name}, age {self.age}"

print(my_dog)  # Buddy, age 4

Inheritance

Inheritance is used when creating specialized classes by letting you define a new class based on an existing one.

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

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

# Alternative syntax
class Dog(Animal):
    def __init__(self, name, breed):
        Animal.__init__(self, name)
        self.breed = breed
  • Dog inherits from Animal class Dog(Animal)
  • super().__init__(name) calls the parent's __init__() it does not take self as an attribute

One class can also contain instances of other classes, this is known as composition.

class Tail:
    def __init__(self, length):
        self.length = length

class Bird:
    def __init__(self, name):
        self.name = name
        self.tail = Tail(15)

Python supports multiple inheritance. This allows one class to combine features from more than one parent class.

class Class3(Class2, Class1):
    def __init__(self, param1, param2, param3, param4):
        Class1.__init__(self, param1, param2)
        Class2.__init__(self, param3, param4)

Mixins

A mixin is a class that provides methods to other classes but is not a parent class in the traditional sense. They are used to avoid duplication when several classes need similar methods.

class JsonMixin:
    """Provides JSON export functionality."""
    def to_json(self):
        import json
        return json.dumps(self.__dict__)

class User(JsonMixin):
    def __init__(self, name):
        self.name = name
  • Mixins don't usually need an __init__() method
  • You include them before the main class in parentheses