• No results found

So far we’ve seen lots of functions: built-in functions, functions inside modules, and functions that we’ve defined. A method is another kind of function that is attached to a particular type. There are str methods, int methods, bool methods, and more—every type has its own set of methods. In this chapter, we’ll explore how to use methods and also how they differ from the rest of the functions that we’ve seen.

7.1 Modules, Classes, and Methods

In Section 6.1, Importing Modules, on page 100, we saw that a module is a kind of object, one that can contain functions and other variables. There is another kind of object that is similar to a module: a class. You’ve been using classes all along, probably without realizing it: a class is how Python repre-sents a type.

You may have called built-in function help on int, float, bool, or str. We’ll do that now with str (notice that the first line says that it’s a class):

>>> help(str)

Help on class str in module builtins:

class str(object)

| str(object[, encoding[, errors]]) -> str

|

| Create a new string object from the given object. If encoding or

| errors is specified, then the object must expose a data buffer

| that will be decoded using the given encoding and error handler.

| Otherwise, returns the result of object.__str__() (if defined)

| or repr(object).

| encoding defaults to sys.getdefaultencoding().

| errors defaults to 'strict'.

|

| Methods defined here:

|

| __add__(...)

| x.__add__(y) <==> x+y

|

| __contains__(...)

| x.__contains__(y) <==> y in x

[Lots of other names with leading and trailing underscores not shown here.]

| capitalize(...)

| S.capitalize() -> str

|

| Return a capitalized version of S, i.e. make the first character

| have upper case and the rest lower case.

|

| center(...)

| S.center(width[, fillchar]) -> str

|

| Return S centered in a string of length width. Padding is

| done using the specified fill character (default is a space)

|

| count(...)

| S.count(sub[, start[, end]]) -> int

|

| Return the number of non-overlapping occurrences of substring sub in

| string S[start:end]. Optional arguments start and end are

| interpreted as in slice notation.

[There are many more of these as well.]

Near the top of this documentation is this:

| str(object[, encoding[, errors]]) -> str

|

| Create a new string object from the given object.

That describes how to use str as a function: we can call it to create a string.

For example, str(17) creates the string '17'.

We can also use str to call a method in class str, much like we call a function in module math. The main difference is that every method in class str requires a string as its first argument:

>>> str.capitalize('browning')

'Browning'

This is how methods are different from functions: the first argument to every string method must be a string, and the parameter is not described in the documentation for the method. This is because all string methods require a string as the first argument, and more generally, all methods in a class require Chapter 7. Using Methods

116

an object of that class as the first argument. Here are two more examples, this time using the other two string methods from the code on page 115. Both of these also require a string as the first argument.

>>> str.center('Sonnet 43', 26)

' Sonnet 43 '

>>> str.count('How do I love thee? Let me count the ways.', 'the')

2

The first method call produces a new string that centers 'Sonnet 43' in a string of length 26, padding to the left and right with spaces.

The second method call counts how many times 'the' occurs in 'How do I love thee? Let me count the ways.' (once in the word thee and once as the penultimate word in the string).

7.2 Calling Methods the Object-Oriented Way

Because every method in class str requires a string as the first argument (and, more generally, because every method in any class requires an object of that class as the first argument), Python provides a shorthand form for calling a method where the object appears first and then the method call:

>>> 'browning'.capitalize()

'Browning'

>>> 'Sonnet 43'.center(26)

' Sonnet 43 '

>>> 'How do I love thee? Let me count the ways.'.count('the')

2

When Python encounters one of these method calls, it translates it to the more long-winded form. We will use this shorthand form throughout the rest of the book.

The help documentation for methods uses this form. Here is the help for method lower in class str. (Notice that we can get help for a single method by prefixing it with the class it belongs to.)

>>> help(str.lower)

Help on method_descriptor:

lower(...)

S.lower() -> str

Return a copy of the string S converted to lowercase.

Contrast that documentation with the help for function sqrt in module math:

>>> help(math.sqrt)

Help on built-in function sqrt in module math:

sqrt(...) sqrt(x)

Return the square root of x.

The help for str.lower shows that you need to prefix the call with the string value S; the help for math.sqrt doesn’t show any such prefix.

The general form of a method call is as follows:

«

expression

»

.

«

method_name

»

(

«

arguments

»

)

So far every example we’ve seen has a single object as the expression, but any expression can be used as long as it evaluates to the correct type. Here’s an example:

>>> ('TTA' + 'G' * 3).count('T')

2

The expression ('TTA' + 'G' * 3) evaluates to the DNA sequence 'TTAGGG', and that is the object that is used in the call on string method count.

Here are the steps for executing a method call. These steps are quite similar to those for executing a function call in Section 3.5, Tracing Function Calls in the Memory Model, on page 40.

1. Evaluate «expression»; this may be something simple, like 'Elizabeth Barrett Browning' (a poet from the 1800s), or it may be more complicated, like ('TTA' + 'G' * 3). Either way, a single object is produced, and that will be the object we are interacting with during the method call.

2. Now that we have an object, evaluate the method arguments left to right.

In our DNA example, the argument is 'T'.

3. Pass the result of evaluating the initial expression as the first argument, and also pass the argument values from the previous step, into the method. In our DNA example, our code is equivalent to str.count('TTAGGG', 'T'). 4. Execute the method.

When the method call finishes, it produces a value. In our DNA example, str.count('TTAGGG', 'T') returns the number of times 'T' occurs in 'TTAGGG', which is 2.

Chapter 7. Using Methods

118