Classes

What is a Class?

A class is an object that can contain variables and methods. Multiple instances of the class can be created and used independent of eachother.

Why Should I Use Classes?

Classes are a core principle of object-oriented languages, and play a key role in reducing the amount of reused code. Often, you'll find that you need to think of a piece of code like an object, and when coming across a problem like this, you'll most likely want to use an object. For instance, say you're writing a game with a quest system, you'll probably want to make a quest manager object, with methods to add, create and remove quests, and then have a quest class, with methods to update, find info about, and complete the quest, which each quest will subclass.

Using Classes

How to Create a Class

The code below will create an empty class.

class MyClass:
    pass

Inheritance

What is Inheritance?

Inheritance is when a class extends another, or multiple others.

When a class is extended by another, the new class will contain everything the extended class had.

How to Inherit From a Class

To inherit from another class, simply type it's name inside a set of parentheses..

class MyClass(object):
    pass

To inherit from multiple, simply place a comma after each class you would like to extend

class MyClass(object, str):
    pass

If no class is given to inherit, the class will inherit from object.

Class Initialiser

What is the Class Initialiser?

The class initialiser is a method that is run whenever an instance of the class is created. It is where instance variables will be created.

class MyClass:
    def __init__(self):
        self.name = "Monty"

Initialiser Arguments

You might find that you want to pass arguments into the class for it to use. These arguments can be passed after self.

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

Now the name can be retrieved from an instance of the class.

Running the Initialiser of an Extended Class

If you extend from a class that sets variables in it's initialiser, you will notice that those variables will not be set in your extended class if you have an initialiser. This is because the extended class's constructor is never run. To fix this, you will need to run the initialiser inside yours.

class MyClass(OtherClass):
    def __init__(self):
        OtherClass.__init__(self)

Methods

What is a Method?

A method is what functions of a class are called. They are the same as normal functions, except they take an additional argument for the first parameter, the class.

How to Create a Method

def my_method(self):
    pass

Class Variables

What is a Class Variable?

A class variable is a variable that belongs to the class. In every instance of the class, class variables will always stay the same. They are defined before the constructor.

class MyClass:
    my_variable = "Hello."

Instance Variables

What is an Instance Variable?

An instance variable is a variable of the class that can be used from an instance. They are defined in the constructor of the class.

class MyClass:
    def __init__(self):
        self.my_variable = "Hello."

If the variable name lacks the self., it will instead be a local variable.

Instances

What is an Instance?

An instance of a class contains everything that the class has. The instance can use the class methods and variables, and can even have those variables contain different things.

How to Create an Instance

To create an instance, you simply type the name followed by an empty set of parentheses.

MyClass()

If the class takes arguments in the constructor, they will need to be given in the instance.

MyClass("Monty")

Example

class QuestManager(object):
    def __init__(self):
        self.quests = []
        self.active = 0
        
    def start(self, quest):
        print(f"Started: {quest.name}")
        
        quest.start()
        self.quests.append(quest)
        
    def ditch(self, quest):
        "Ditches the given quest"
        print(f"Ditched: {quest.name}")
        
        quest.ditch()
        self.quests.remove(quest)
        
    def ditch_current():
        "Ditches the current quest"
        self.ditch(self.get_active())
        
    def complete_current():
        self.complete(self.get_active())
        
    def get_active():
        return self.quests[self.active]
class Quest(object):
    def __init__(self, name, description):
        self.name = name
        self.description = description
        
    def start(self):
        pass
        
    def complete(self):
        pass
        
    def ditch(self):
        pass
manager = QuestManager()
fetch_sword = Quest("Fetch Sword", "Delve into a dungeon and retrieve a sword.")

Last updated