Class (computer programming)

In object-oriented programming, a class is a type of object. Objects of a certain class are said to be instances of that class. For example, "spam" is an instance of the String class.

Classes typically have both data (often called attributes) and functions (called methods) associated with them. Attributes that are different for each instance (rather than being constant) are also called instance variables.

Classes in Python

Basics

Suppose you have a hypothetical Die class. To create a new (instance of) Die the syntax would be:

myDie = Die(6) # creates a Die with 6 sides

Behind the scenes this calls Die's __init__ method (see below).

Python uses a period after the instance name (myDie in this example) to access attributes and methods:

myDie.roll()  # call Die's roll method for myDie
myDie.top = 4 # change the attribute top (but see note on public variables below)

Methods are called with parentheses (and, optionally, parameters) just like functions.

Creating New Classes

The syntax for creating your own classes in Python is rather predictable:

class myClass:

Everything inside the class after this line should be indented.

Methods

Methods are basically functions tied to classes, and the syntax is similar:

def getTop(self):
    return self.__top

The first major difference is that the first parameter of any method should always be self. self refers to the instance of the class the function was called on. For example, when we call myDie.getTop() self will refer to myDie.

The second major difference is that methods can be private. We indicate this in Python by preceding them with an underscore:

def _examplePrivateMethod(self, n):
    ...

Private methods cannot be called from outside the class. That is, we couldn't do myDie._examplePrivateMethod(4), but we could do self._examplePrivateMethod(4) from within the class. They are often useful when writing 'helper' methods that are used by other methods in a class, but aren't meant to be called on their own in other parts of your program.

Special Methods

The third major difference between methods and functions is that Python allows you to define many 'special' methods that are called in unusual ways. All special methods have two underscores before and after their name when you define them.

The most important special method is __init__ (short for initialize). This is the method called when you create new instances of a class, so it has to perform any necessary setup. This usually just means initializing any instance variables (see below) the class needs. If you don't define an __init__ method for your class Python will insert a blank one at runtime (so you'll still be able to create instances of your class, but no variables will be initialized). You can define init to take any number of arguments, but as usual the first one must be self. For example, the following init takes one argument (plus self), and creates two instance variables:

def __init__(self, name):
    self.__name = name
    self.__score=0

Other useful special methods (see below for a link to the full ist):

  • __str__(self) should return a human readable string representation of the object. To call it, use str(myObject)
  • __eq__(self, other) should return a boolean, whether or not self and other are equivalent. This would typically just be when their instance variables match. To call it, use myObject == otherObject.
  • __add__(self, other) should return the sum of self and other, which can mean whatever you want it to. To call it, use myObject + otherObject.

Attributes

Attributes are variables associated with a class. If they change from instance to instance (rather than being constant for all instances of a class) they're also called instance variables. Instance variables are typically initialized in __init__, as in the example above.

Like methods, attributes can be either public or private. Private attributes are created with two underscores preceding the variable name (as in the init example above). Private attributes can't be accessed from outside the class. This is usually desirable, because then other parts of your program can't accidentally change them without going through accessors (see below) beforehand, which is a common source of bugs. In general, it is good practice to make every instance variable private unless you have an explicit reason not to.

Accessor and Modifier Methods

However, it's fairly common for code outside a class to need to read attributes of a class. To permit this while still keeping variables private, you can write accessor methods to retrieve the values of variables, and modifier methods to change them, where appropriate. This approach allows the class to better control its variables (to ensure a list stays sorted, or a counter stays updated, for example).

Usually, methods like this have names like 'getName', and 'setTop'. For this reason they're often also called getters and setters.

Note that mutable data structures like lists are passed by reference, so if you're not careful a getList method would return your actual list. Then any modifications the caller made would be reflected in the original list, negating the advantages of private variables. As a workaround, you can instead return a copy of the data structure, or the list converted to a tuple by a type conversion function.


See Also

  • The isinstance function provides a way to test whether an object is an instance of a certain class in Python.
  • Classes in the Python Tutorial.
  • A full list of possible special methods.