How to create a Python class



The basics

This is a Python class.

The below example shows how you can create a class named "Cat" using the keyword "class".

Following this you would have a constructor called "__init__" defined using the "def" keyword

The constructor by default requires a parameter called "self" to refer to this class instance



class Cat:  # This is our "Cat" class
def __init__(self):
    pass  # Empty placeholder

# Creating an instance of the class
cat = Cat()


Variables

Now let us add some variables to our class.

Below I will show two common uses of variables inside a class

Following this you would have a constructor called "__init__" defined using the "def" keyword

The constructor by default requires a parameter called "self" to refer to this class instance



class Cat:  # This is our "Cat" class

    classType = "Animal"  # Variables accessible to all instances of this class

    def __init__(self, name):  # "name" is passed as a parameter in the constructor
        self.name = name  # Variables accessible to this instance only

# Creating an instance of the class
catTommy = Cat("Tommy")  # "name" is passed as "Tommy"

# Print our cat's name to the console
print(catTommy.name)  # [Console] --> Tommy


Functions

Now let us add some functions to our class.

Similar to the "__init__" you will define a function using "def" followed by a function name and rounded brackets which hold any parameters and the "self" key word.



class Cat:  # This is our "Cat" class

    classType = "Animal"  # Variables accessible to all instances of this class

    def __init__(self, name):  # "name" is passed as a parameter in the constructor
        self.name = name  # Variables accessible to this instance only
        self.age = 0

    # Increases the cats age by the value passed in
    def increaseAge(self, value):
        self.age += value  # Or self.age = self.age + value
        return self.age  # Returns the new age of the cat using the "return" keyword


# Creating an instance of the class
catTommy = Cat("Tommy")  # "name" is passed as "Tommy"

# Print our cat's age to the console
print(catTommy.increaseAge(5))  # [Console] --> 5