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:
>>> class MyClass(object): pass
>>> myinstance = MyClass()
>>> myinstance.myvariable = 3
>>> print myinstance.myvariable
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:
>>> class MyClass(object):
... z = 2
... def __init__(self, a, b):
... self.x = a
... self.y = b
... def add(self):
... return self.x + self.y + self.z
...
>>> myinstance = MyClass(3, 4)
>>> print myinstance.add()
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.