Classes

Classes contain functions and variables. They usually have a constructor called init which is a special function which is called when an instance of a class is created.
class MyAmazingClass:
    def __init__(self,coeff):
        # Your init code here.
        self.mylocalcoeff = coeff

    def doSomeProcessing(self,data):
        # we process data
        data = data * self.mylocalcoeff
        return data
(!) Note the special variable “self” which is the first argument of every method in a class. Variables which are part of the class are references by “self”. For example the constructor argument “coeff” is saved in the class as “mylocalcoeff” and is then available throughout the lifetime of the class as “self.mylocalcoeff”. When we call the method “doSomeProcessing” then “self.mylocalcoeff” is multiplied with the “data” argument and the result is returned. Anything which hasn't got “self.” in front of it will be forgotten after the function has terminated. In this way you distinguish which variables are kept for the lifetime of the class or are just used temporarily.

Classes are just types and need to be instantiated:

f = MyAmazingClass(5)
a = f.doSomeProcessing(10)
b = f.doSomeProcessing(20)
which will give us 50 as a result for the variable “a” and 100 for the variable “b”. The variable “f” is the instance of the class MyAmazingClass and the argument initialises self.mylocalcoeff with 5.



github / contact

Creative Commons License