Classes

Python has a class mechanism distinct from the object-orientation already explained. A class in Python is not much more than a collection of methods and a way to create class instances. Class methods are ordinary functions whose first parameter is the class instance; they are called using the method notation.

For instance, a class can be defined as follows:

class Foo:
   def meth1(self, arg): ...
   def meth2(self): ...
A class instance is created by x = Foo() and its methods can be called thus:
x.meth1('Hi There!')
x.meth2()
The functions used as methods are also available as attributes of the class object, and the above method calls could also have been written as follows:
Foo.meth1(x, 'Hi There!')
Foo.meth2(x)
Class methods can store instance data by assigning to instance data attributes, e.g.:
self.size = 100
self.title = 'Dear John'
Data attributes do not have to be declared; as with local variables, they spring into existence when assigned to. It is a matter of discretion to avoid name conflicts with method names. This facility is also available to class users; instances of a method-less class can be used as records with named fields.

There is no built-in mechanism for instance initialization. Classes by convention provide an init() method which initializes the instance and then returns it, so the user can write

x = Foo().init('Dr. Strangelove')

Any user-defined class can be used as a base class to derive other classes. However, built-in types like lists cannot be used as base classes. (Incidentally, the same is true in C++ and Modula-3.) A class may override any method of its base classes. Instance methods are first searched in the method list of their class, and then, recursively, in the method lists of their base class. Initialization methods of derived classes should explicitly call the initialization methods of their base class.

A simple form of multiple inheritance is also supported: a class can have multiple base classes, but the language rules for resolving name conflicts are somewhat simplistic, and consequently the feature has so far found little usage.