How to Make and Use Classes in Python

How to Make and Use Classes in Python

Overview

This article will explain how to make classes in Python, the advantages of using them and define other terminology related to classes.

Materials

  • Computer

  • Python

  • Terminal or IDE

Making a Class

To initialize a class in Python, write "class", assign a class name and a colon afterward

class Name_of_the_class:
    variable_1 = 3
    variable_2 = "Sample Text"

Within the class block, variables can be defined within this space. Directly printing these declared variables outside the class will not be read.

How to Execute Classes

A class can be executed by printing out the variables within the class by using methods. A method is created by taking the name of the class followed by a "." and then one of the names of the variable the class contains. An object or variable outside of the class can be created to print the contents of the class with the same methodology.

Creating a Class, Methods and Printing Data

class Name_of_the_class:
    variable_1 = 3
    variable_2 = "Sample Text"

print(Name_of_the_class.variable_1)

assign_class_to_variable = Name_of_the_class
print(assign_class_to_variable.variable_2)

If the class is directly printed, it outputs in the Terminal to confirm it is a class and the name of the class that it was given in the Python file.

print(Name_of_the_class)

Why use Classes

Classes are good to implement in scripting as they reduce writing the same code over and over again. Implementing functions can also reduce writing the same code, though classes can implement functions within their block and generally use more methods to execute commands too.

Using Classes and Functions Together

Below is an example of how to use a class and a function without a constructor or the self variable:

class Name_of_the_class:
    def function():
        variable_name = "Hello"
        return variable_name

class_info = Name_of_the_class.function()
print(class_info)

Writing a Class with a Constructor

As stated before, classes can use functions and often use constructors. They are also functions formatted shown below:

def __init__(self, variable1, variable2............last_variable):

The "def __init__()" is a constructor and is efficient in declaring many objects within their function block that can be called upon. Below is a constructor within a class and methods are used to print out the class variable data:

Using a Constructor and Methods in a Class to Print Data

class Shapes:
    def __init__(self, shape1, shape2):
        self.shape1 = shape1
        self.shape2 = shape2

the_shapes = Shapes("Triangle", "Square")
print(the_shapes.shape1)
print(the_shapes.shape2)

Why Self is Important

First, the class was declared and then the constructor. In the constructor, many variables and the word "self" are initialized. Outside the class, an object or a variable in this case "the_shapes" was declared. The keyword "self" within the class is a placeholder for variables that use the class to print out its content. This example created the variable "the_shapes" and is assigned to print variables from the "Shapes" class by using methods. For it to use print the methods successfully, the class has to recognize the variable that is using its class. When Python prints "the_shapes.shape1" it is rerouted back to the class to use self to substitute it as "the_shapes" momentarily for it to use methods outside the class to print out other variables. "self" applies this logic to any variable that tries to use an assigned class.

For best practices, classes usually have a constructor and several functions without constructors to execute methods.

What are SuperClasses and SubClasses

In Python, a class can be defined for its properties to be inherited or used by other classes. The original class is the superclass and the other class or classes that inherits or uses the superclass' properties is the subclass.

How Inheritance Works

Inheritance works by first declaring a class and then another class. For the second class, put the name of the first class in the second class's parenthesis and it will inherit all of its properties.

class Name_Of_Superclass:
    def __init__(self, variable1, variable2):
        self.variable1 = variable1
        self.variable2 = variable2

class Subclass1(Name_Of_Superclass):
    pass

a = Name_Of_Superclass
print(a(1, 2).variable1, a(1, 2).variable2)

Misusing Inheritance

When using inheritance, avoid overwriting what was previously declared. An example would be overwriting the constructor in the subclass as shown below:

class Name_Of_Superclass:
    def __init__(self, variable1, variable2):
        self.variable1 = variable1
        self.variable2 = variable2

class Subclass2(Name_Of_Superclass):
    def __init__(self, variable1):
        self.variable1 = variable1

b = Subclass2
print(b(3).variable1)
print(b(4,5).variable2)

The constructor in subclass2 was overwritten by repeating the line "def __init__(self, ......)". Constructors specify how many expected arguments are expected to be received, and this example overwritten the constructor to accept two arguments. The line of code "print(b(4,5).variable2)" resulted in an error since variable2 is not a defined parameter and it did not expect to receive "5" or three arguments. It only expected the self and another input as a total of two arguments.

Prevent Overwriting Constructors by using "super()"

Below the superclass defined variable1 and variable2. The subclass made its constructor and defined variable1, variable2, and variable3 but did not make the self methods for variable1 and variable2. By stating the line "super().__init__(variable1, variable2)" looks within the superclass for the subclass to see if the self.methods were defined for the variables that were not defined in the subclass. The names of the variables and the statement "super().__init__()" are case-sensitive.

class Name_Of_Superclass():
    def __init__(self, variable1, variable2):
        self.variable1 = variable1
        self.variable2 = variable2

class Subclass(Name_Of_Superclass):
    def __init__(self, variable1, variable2, variable3):
        super().__init__(variable1, variable2)
        self.variable3 = variable3

a = Subclass(1, "2", 3)
print(a.variable1)
print(a.variable2)
print(a.variable3)

Another Way to Use Functions in Classes to Return Values

Another common example is to define all the methods within the constructor and then define another function to return the values of the methods:

class Name_of_Superclass():
    def __init__(self, variable1):
        self.variable1 = variable1

    def function(self):
        return self.variable1

class Subclass(Name_of_Superclass):
    def __init__(self, variable1):
        super().__init__(variable1)

a = Subclass("Hello")
print(a.variable1)