Recommended Books

Python Classes



What are Python Classes?

A class is used to define the characteristics of an object (fields and properties) and the things it can do (methods).

The simplest definition for a class is that it is used a blueprint or model for creating objects.

Other Terminology:

An Instance is the class object that is created at run time. It can be called the physical manifestation of a class. An instance is created when a class is assigned to a variable.

The terms object and instance are very interchangeable here, so expect to hear both. The best way to describe is that an object is the actual thing made using the blueprint (class) and the instance is a virtual copy of that object.

Methods are another important term. A method is a function that belongs to an object. This will be more clear later on as we define methods for our classes.

constructor is a special kind of method that Python calls when it creates an object/instance.  Python uses the constructor to perform tasks such as initializing any variables that the object will need when it starts.


Classifying Classes

This is an issue that comes up when you’re creating multiple classes. People tend to miss the point of a class. A class is meant to hold information regarding a certain topic or field. For instance, one might create a class called student. You can expect it to have student related variables and methods, like Roll_No, Grade, School etc. Including variables like, Avg rainfall, Stock price, Seasons would ruin the point of having a student class.

Similarly, don’t create a massive class filled with all kinds of different fields and topics. For instance, if you’re creating classes for all the people in a school. Make three classes, one for the students, one for the teachers and one for the staff. This allows for greater organization and readability.


Python Classes Syntax:

The keyword used to create classes is class. Below is an example class, complete with methods (functions) and the __init__ function (the constructor) which is used to initialize variables.

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

    def checkage(self):
        if self.age < 18:
            print("Underage")
        else:
            print("18 or Above")  

As you can see, we have two methods in the example above. The first is the constructor which takes input and initializes variables which are to be used later.

The other method, checkage() is used to check whether the age of student is above or below 18. This function will not run unless called using it’s instance or object.

It is compulsory for every class method to have self as it’s first parameter! The self parameter is a reference to the current instance of the class. Having this is essential for accessing variables in a class.


Creating Instances

Assigning a class to a variable creates an object, or what we may call, a class instance.

Note the two arguments that we passed into the class. If you look at the example above, there are three parameters. Python will take care of the self argument for you, so you just have to input 2 arguments.

Student1 = Student("Naomi",20)
Student2 = Student("Gordan", 17)

Calling Class Methods

Once you’ve created a class object and passed your input arguments you’ll want to begin using the various methods created within it. The format is pretty simple. “Object name” followed by a dot, and then the function name.

The example below calls the method checkage.

Student1.checkage()
Student2.checkage()
# Output
18 or Above
Underage

Accessing variables in a class

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

Student1 = Student("Naomi",20)

Keep note of the two variables shown in the code above. (The method was removed as it’s not necessary for this section) We’ll be going through how to manipulate these variables outside the scope of the class.

Regardless of the operation being performed, it’s important for us to reference the object the variable belongs to. This is because, like functions, classes have their own local scope as well. You may declare all the variables in a class as global, but that’s not very good practice.

Print

print(Student1.age)
print(Student1.name)

Assignment

Student1.age = 20
Student1.name = "Sarah"

Delete

del Student1.age

You can also delete an object entirely using the del command.

del Student1

So why use Python classes?

Chances are by now you’ve gone through alot of material already and have already begun writing code. You might ask, “Why should I use Classes?”. The best way to find out is to begin using classes yourself. Experience is the best teach. Here are some reasons why anyway.

  • Re-usability. Similar to functions, classes greatly improve the re usability of your code since its the same methods and variables begin used again and again, without the need to rewrite all of it. Here’s a test. Try re-writing the example above in a non class approach. You’ll realize just how inefficient it is, especially on a project of a larger scale, where hundreds of objects would be required.
  • Maintainability. Both due to the simpler structure laid out by Python classes, as well as a reduced number of lines, the code is either to maintain and debug.
  • Making Custom exceptions. If the inbuilt exceptions aren’t enough for you, you can make your own custom exceptions using classes.

Classes are a vast topic and can’t be covered in a single page. Head over to our advanced class section which covers other python classes related concepts like inheritance, and further uses.