A simple guide to classes in python

Classes can be a really useful way to simplify and unify your code.

In order to create a class in python you have to use the following syntax:

class yourClassName():

    (class functions (or methods) go in here)

In order to define a class method, you use the same syntax as creating a function:

def yourClassMethod(self, otherParameters):

self is a special parameter that is required for every class method. If you try to call the method and the method doesn't contain the self parameter you will get the following error:

TypeError: yourClassMethod() takes x positional arguments but x+1 were given

where x is the amount of other parameters. This could be 0 as you do not need any other parameters, however you can use other parameters similarly to parameters in functions.

The self parameter is used to allow self.attribute or self.method() (re-named appropriately). This either gets the named attribute or calls the named method of the current class (object).

Attributes are set values in a class that are available to any of the functions in the class. They can also be accessed from outside the class using classObject.attribute. Attributes can be set inside a class using self.attribute = x or from outside the class using classObject.attribut = x. It is generally better practice to set from inside a class. Their value can be obtained by x = classObject.attribute or x = self.attribute from outside or inside a class, respectively.

A class object is an object that has the attributes and methods that are described in your class. you can create a new class object with the syntax classObject = yourClassName().

There are a few special functions that you can define inside your class. The most used one is probably __init__. This is a function that runs when you first create your class, and is called a constructor. This follows the same rule as other class functions as in it requires the self parameter. The most basic use of __init__ would be to do:

def __init__(self):

However, you can also add other parameters to the __init__ function, and these parameters will have to be put in the brackets when you first define the class object e.g. classObject = yourClassName(parameter). This will pass the parameter(s) into __init__. If you don't want to have to pass in a parameter, but you want the option available, you can do something like

def __init__(self, parameter=None):

This will set the value of the parameter to None if no matching parameters are passed in. This can also be expanded to include multiple optional parameters, but keep in mind that the previous parameters have to be passed in if you want to pass in, say, the third parameter in an __init__ function. This can also be used for other functions, both inside and outside of classes.

Comment Stream