How to Create a Class Definition in Python - dummies

How to Create a Class Definition in Python

By John Paul Mueller

A class need not be particularly complex. In fact, you can create just the container and one class element in Python and call it a class. Of course, the resulting class won’t do much, but you can instantiate it (tell Python to build an object using your class as a blueprint) and work with it as you would any other class.

The following steps help you understand the basics behind a class by creating the simplest class possible.

1Open a Python Shell window.

You see the familiar Python prompt.

2Type the following code (pressing Enter after each line and pressing Enter twice after the last line):

class MyClass:
 MyVar = 0

The first line defines the class container, which consists of the keyword class and the class name, which is MyClass. Every class you create must begin precisely this way. You must always include class followed by the class name.

The second line is the class suite. All the elements that comprise the class are called the class suite. In this case, you see a class variable named MyVar, which is set to a value of 0. Every instance of the class will have the same variable and start at the same value.

3Type MyInstance = MyClass() and press Enter.

You have just created an instance of MyClass named MyInstance. Of course, you’ll want to verify that you really have created such an instance. Step 4 accomplishes that task.

Typing a new class in Python

4Type MyInstance.MyVar and press Enter.

The output of 0 demonstrates that MyInstance does indeed have a class variable named MyVar.

Testing a class in Python.

5Type MyInstance.__class__ and press Enter.

Python displays the class used to create this instance. The output tells you that this class is part of the __main__ module, which means that you typed it directly into the shell.