Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is class in Python

Understanding Classes in Python

When you're just starting to learn programming, hearing the word "class" might bring to mind a group of students in a school. In the world of programming, particularly in Python, a class is somewhat similar—it's a blueprint for creating objects, which are individual instances of data structures that can hold both data and functions that manipulate that data.

What is a Class?

Think of a class as a recipe. A recipe contains the instructions on how to make a dish, but it is not the dish itself. Similarly, a class in Python defines how to build an object, but it is not the object. You can use the same recipe to make multiple dishes, and likewise, you can create multiple objects from a single class.

Defining a Class in Python

To define a class in Python, you use the class keyword followed by the class name and a colon. Inside the class, you define functions that belong to the class, which are called methods, and variables that are called attributes.

Here's a simple example:

class Dog:
    species = "Canis familiaris"  # Class attribute

    def __init__(self, name, age): = name  # Instance attribute
        self.age = age    # Instance attribute

    def description(self):
        return f"{} is {self.age} years old"

    def speak(self, sound):
        return f"{} says {sound}"

In this example, Dog is a class that represents a dog with a name and age. The species attribute is a class attribute, which means it is the same for all instances of the class. The __init__ method is a special method called a constructor, which is called when you create a new instance of the class. The self parameter refers to the current instance of the class and is used to access attributes and methods.

Creating Objects from a Class

Once you have a class defined, you can create objects from it. Here's how you might create two Dog objects:

my_dog = Dog("Rex", 6)
your_dog = Dog("Fido", 3)

Each dog has its own name and age, but they share the species attribute because it is a class attribute.

Methods: Adding Behavior to Objects

Methods are functions defined within a class that describe the behaviors of an object. In our Dog class, we have a description method that returns a string containing the dog's name and age, and a speak method that simulates the dog making a sound.

Here's how you can use these methods:

print(my_dog.description())  # Output: Rex is 6 years old
print(your_dog.speak("Woof"))  # Output: Fido says Woof

The __init__ Method: The Constructor

The __init__ method is a special method in Python classes. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Notice the self variable represents the instance of the object itself and is used to access variables that belong to the class.

Instance vs. Class Attributes

Attributes can be of two types: instance attributes and class attributes. Instance attributes are specific to each object, like name and age in our Dog class. Class attributes are shared by all instances of the class. In our Dog class, species is a class attribute.

Inheritance: Extending Classes

Inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, and the classes that we derive from are called base classes. Derived classes (descendants) override or extend the functionality of base classes (ancestors).

Here's an example of inheritance in Python:

class Bulldog(Dog):  # Inherits from Dog class
    def run(self, speed):
        return f"{} runs at {speed} mph"

Here, Bulldog is a derived class that inherits from Dog. It has all the attributes and methods of Dog, plus a new method run that is specific to Bulldog.

Polymorphism: One Interface, Many Forms

Polymorphism allows us to define methods in the child class with the same name as defined in their parent class. As an example, if we have a method speak in our Dog class, we can define a method with the same name in our Bulldog class that does something different.

class Bulldog(Dog):  # Inherits from Dog class
    def speak(self, sound="Gruff"):
        return super().speak(sound)

Here, Bulldog has its own version of speak, but it uses super() to call the method from the parent class if needed.

Encapsulation: Keeping It Together

Encapsulation is the bundling of data with the methods that operate on that data. It restricts direct access to some of an object's components, which is a way of preventing accidental interference and misuse of the data. In Python, this is done through the use of private variables and methods, which are denoted by double underscores at the beginning.

class Computer:
    def __init__(self):
        self.__maxprice = 900

    def sell(self):
        print(f"Selling Price: {self.__maxprice}")

    def setMaxPrice(self, price):
        self.__maxprice = price

c = Computer()

# Try to change the price
c.__maxprice = 1000

# Using setter function

In this example, __maxprice is a private attribute, and it cannot be accessed directly from outside the class.

Conclusion: The Power of Classes in Python

Classes are a fundamental part of Python and object-oriented programming. They allow us to create complex data structures that can contain both data and functions to process that data. By using classes, Python programmers can create reusable code that is organized, efficient, and easy to maintain.

As you continue your journey in programming, remember that a class is like a blueprint for creating objects. Just like a blueprint can be used to construct buildings that look the same but serve different purposes, classes allow you to create objects that follow the same structure but contain different information.

The concepts of inheritance, polymorphism, and encapsulation might seem complex now, but as you practice and create more classes, they will become second nature. These principles help programmers write code that is modular, easy to debug, and versatile.

In the end, classes are all about creating your own data types that have their own logic and representation. They are a powerful tool in your programming toolkit, and mastering them will open up a world of possibilities in your coding projects. Keep practicing, keep experimenting, and most importantly, have fun with it!