Coming Attraction Objects

Have you noticed anything strange about the syntax of the file processing examples? To apply an operation to a file, we use dot notation. For example, to read from infile we type This is different from the normal function application that we have used before. Afterall, to take the absolute value of a variable x, we type abs(x) , not x.abs().

In Python, a file is an example of an object. Objects combine both data and operations together. An object's operations, called methods, are invoked using the dot notation. That's why the syntax looks a bit different.

For completeness, I should mention that strings are also objects in Python. If you have a relatively new version of Python (2.0 or later), you can use string methods in place of the string library functions that we discussed earlier. For example, myString.split()

is equivalent to string.split(myString)

If this object stuff sounds confusing right now, don't worry; Chapter 5 is all about the power of objects (and pretty pictures, too).

0 0

Post a comment