class

Because Python is dynamically typed, Python classes and objects may seem odd. In fact, you do not need to define the member variables (attributes) when declaring a class, and different instances of the same class can have different attributes. Attributes are generally associated with the instance, not the class (except when declared as “class attributes”, which is the same as “static member variables” in C++/Java).

Here is an example:

  1. >>> class MyClass(object): pass
  2. >>> myinstance = MyClass()
  3. >>> myinstance.myvariable = 3
  4. >>> print myinstance.myvariable
  5. 3

Notice that pass is a do-nothing command. In this case it is used to define a class MyClass that contains nothing. MyClass() calls the constructor of the class (in this case the default constructor) and returns an object, an instance of the class. The (object) in the class definition indicates that our class extends the built-in object class. This is not required, but it is good practice.

Here is a more complex class:

  1. >>> class MyClass(object):
  2. ... z = 2
  3. ... def __init__(self, a, b):
  4. ... self.x = a
  5. ... self.y = b
  6. ... def add(self):
  7. ... return self.x + self.y + self.z
  8. ...
  9. >>> myinstance = MyClass(3, 4)
  10. >>> print myinstance.add()
  11. 9

Functions declared inside the class are methods. Some methods have special reserved names. For example, __init__ is the constructor. All variables are local variables of the method except variables declared outside methods. For example, z is a class variable, equivalent to a C++ static member variable that holds the same value for all instances of the class.

Notice that __init__ takes 3 arguments and add takes one, and yet we call them with 2 and 0 arguments respectively. The first argument represents, by convention, the local name used inside the method to refer to the current object. Here we use self to refer to the current object, but we could have used any other name. self plays the same role as *this in C++ or this in Java, but self is not a reserved keyword.

This syntax is necessary to avoid ambiguity when declaring nested classes, such as a class that is local to a method inside another class.