A brief introduction to object-oriented programming in Python

November 30, 2003


Object-oriented programming is easy. An object is just some data and some code for manipulating it, all bound up into something that will fit in one variable. So object-oriented programming is just a way to organize a program or a part of a program. It's often a good way, but there's no magic to it.


An object is created from a sort of a template called a "class" and an object is often called in "instance" of its class. Here's the simplest possible Python class:


>>> class c:

...   pass

...


I can create instances of that class by putting parentheses after the class name (it looks like I'm calling the class as though it were a function):


>>> o1=c()


I can create any number of instances of that class and they're all independent:


>>> o2=c()

>>> o3=c()


Objects store data in "attributes". You can get at an object's attributes by using a dot and the attribute's name:


>>> o1.wibble=42

>>> o1.wibble

42


Objects can have functions as attributes. Function attributes are routinely called "methods". Here's a small example:


>>> class c2:

...   def getValAsDouble(self):

...     return self.val*2

...

>>> o4=c2()

>>> o4.val=42

>>> o4.getValAsDouble()

84


I bet that's reasonably clear, except maybe for that "self" thing. The reason for self is this: when I'm using an instance, it's in a variable (o4, myVar, aGratuitouslyLongVariableName, or whatever) so I know the name to use when I access its attributes. But back at the time I was defining the class, I had no way of knowing what variable or variables the class's instances would end up in. So within the methods of a class, I need a way to refer to the particular instance in question. That value is always passed as the first argument to a method and it's conventionally called "self".


For relatively obvious reasons, the instances of a class generally have different data in their attributes but have the same methods.


There are some methods that are automatically run by Python at various times. Their names always start and end with a double underscore. The most commonly used one is __init__. It's run just after the object has been created and it's useful for doing things like assigning to attributes at instance-creation time:


>>> class c3:

...   def __init__(self,x):

...     self.val=x

...   def getValAsDouble(self):

...     return self.val*2

...

>>> o5=c3(42) # Arguments are passed to __init__

>>> o5.getValAsDouble()

84


There are some more details, but that should be enough to get started.