Python Classes

A class is a container for other Python objects such as variables and functions.  Everything inside the class must be indented as it is part of the class "block."

Example

Python
class MyClass:
    i=42
  
    def theAnswer(self):
      print(self.i)

After typing that in using the Python Shell, when you run:

Python
MyClass().theAnswer()

You get:

Python
42

Notes

The keyword self is very important.  In order for the function to reference the variable i that the class defines, it must have a reference to the object instance.  Python handles this by passing the object instance as the first parameter of a function defined in the class.  For example, these are also valid statements, as shown using the Python Shell:

Python
>>> c = MyClass()
>>> c.theAnswer()
42
>>> c.i
42
>>> 

The basic construction of a class having no initialization parameters is simply expressed as:

Python
MyClass()

Everything is considered an "object" in Python, including functions.