Object Orientation

After having read this far, you should not be surprised to hear that Python's object orientation is flexible and likely to surprise you if you have been using C-like languages for several years.

The best way to learn Python object-oriented programming (OOP) is to just do it. So, here is a basic script that defines a class, creates an object of that class, and calls a function:

class dog(object): def bark(self):

print "Woof!"

Defining a class starts, predictably, with the class keyword followed by the name of the class you are defining and a colon. The contents of that class need to be indented one level so that Python knows where it stops. Note that the object inside parentheses is there for object inheritance, which is discussed later. For now, the least you need to know is that if your new class is not based on an existing class, you should put object inside parentheses as shown in the previous code.

Functions inside classes work in much the same way as normal functions do (although they are usually called methods), with the main difference being that they should all take at least one parameter, usually called self. This parameter is filled with the name of the object the function was called on, and you need to use it explicitly.

Creating an instance of a class is done by assignment. You do not need any new keyword, as in some other languagesyou just provide empty parentheses. Calling a function of that object is done using a period, the name of the class to call, with any parameters being passed inside parentheses.

Was this article helpful?

0 0

Post a comment