• No results found

Key Points

In document OO Programming in Python (Page 94-100)

Getting Started in Python

2.10 Case Study: Strings and Lists

2.11.1 Key Points

General Use of Objects

• When a new instance of a class is created, we say it is instantiated. Typically this is done using a constructor, which is invoked with the class name followed by parentheses, for examplelist( ).

• An identifier is a name, chosen by a programmer, that is used to keep track of an object.

• An identifier is assigned to an underlying object using the=symbol, as ingroceries = list( ).

1 monthNames = ('January','February','March','April', 2 'May','June','July','August','September',

3 'October','November','December')

4

5 # get input from user

6 original = raw_input('Please enter a date (MM-DD-YYYY): ') 7

8 pieces = original.split('-')

9 month = pieces[0] # this is a string of numerals (e.g., '10') 10 day = pieces[1]

11 year = pieces[2]

12

13 alternate = monthNames[int(month)1] +' '+ day +', '+ year 14 print alternate

FIGURE 2.14: Our complete program for formatting a date.

• A method is invoked using the form object.method(parameters), as in groceries.append('bread').

• When programming in interactive mode, the return value of a function call is displayed within the interpreter.

• An identifier can be assigned to the return value of a function for later use, as in nextToBuy = groceries.pop( ).

• Some methods accept one or more optional parameters. If those parameters are not explic-itly sent, default values are used instead.

• A mutable class is one that contains objects whose state may be changed over time. The listclass is the only example of a mutable class from this chapter.

• An immutable class is one that contains objects whose state cannot be changed, once con-structed. Most of Python’s primitive types are implemented as immutable classes, includ-ingstr,tuple,int,float,long, andbool.

• The semantics of an operator depends upon the type of operands that are used. For example with integers, 13 > 5is true because it compares values. With strings the comparison is evaluated according to alphabetical order, and so '13'>'5'is false.

Sequence types (list, str, tuple)

• Instances of thelist,str, andtupleclasses are designed to represent an ordered sequence of elements. Alistis a mutable sequence of general objects. A tupleis an immutable sequence of general objects. Astris specifically an immutable sequence of characters.

• A position in an ordered sequence is described using an integer index, equal to the number of items that precede the position. By definition, the first element has index 0, so we say that sequences are zero-indexed.

• An individual element of a sequence can be accessed by index, as inwaitlist[0].

• A slice of a sequence, denoted asdata[start:stop:step], is a new sequence that begins at the specified start index, advances by the indicated step size, and continues up to but not including or passing the specified stop index. If not explicitly provided, the start is 0, the stop is the end of the list, and the step size is 1.

• All sequences support containment queries using the syntax value in seqand all report their length usinglen(seq).

• The literal form of alistuses square brackets, as in['cereal','milk','apple'].

• Therangefunction can be used to create a list of integers over a certain range. The syntax range(start, stop, step)is used to create a list, starting at start (0 by default), advancing by the given step size (1 by default), going up to but not including or passing the speci-fied stopping value. For example,range(4)returns[0, 1, 2, 3],range(3,6)returns[3, 4, 5], range(18,6,−5)returns[18, 13, 8].

• Mutator methods supported by thelistclass include:append,insert,pop,remove,reverse, andsort.

• Accessor methods supported by the list class include: countand index, as well as the special methods associated with operators.

• The literal form of astruses either a single quote to begin and end it (e.g., 'bread'), or a double quote to begin and end it (e.g., "bread"), or triple quotes to begin and end it (e.g., """bread""").

• Thestrclass supports many convenient methods that generate a new string that is a variant of an existing string. These include:lower,upper,capitalize,center,ljust,rjust,strip, and replace.

• The strclass supports many convenient methods that return information about a given string. These include:startswith,isalpha,isdigit,islower, andisupper.

• Thestrclass supports two important methods involving lists. Thesplitmethod takes one long string and breaks it up according to a given delimiter, producing a list of pieces. The joinmethod takes a list of strings and reassembles them separated by a delimiter, producing one long string.

• The literal form of atupleuses parentheses, as in('cereal','milk','apple'). Numeric types (int, long, float)

• Theintclass is used to represent integral values.

• Thelongclass is used to represent integral values too large to be directly supported by the computer architecture.

• Thefloatclass is used to represent floating-point numbers, which are similar to the math-ematical notion of a real number, yet with limited precision.

• All numeric types support basic operators for performing arithmetic and for comparing one value to another.

• Division is a bit tricky with numeric types because there are several possible semantics. For example if dividing 14 by 3, a true division results in a floating-point number 4.6666667.

The/operator is typically used to perform true division. In contrast, an integer division results in a quotient of 4 and a separate remainder of 2. The//operator is used to report the quotient, while the%operator is used to report the modulus (i.e., remainder).

Casting among types

• The process of converting data from one type to another is known as casting. In Python, casting is performed by reconstructing a new instance of the desired type, using the existing value as a parameter to the constructor.

• For example str(1776)produces a string representation '1776' of the original integer value.

list('hello')produces the list['h','e','l','l','o']of characters occurring in the given string.

• The syntaxint(x) casts an object to an integer, if possible. For example,int('1776') results in value1776.

• When converting from a floating-point number to an integer, the fractional part is always truncated. Thusint(3.8)evaluates to3.

• The built-in functionroundcan be used to compute the nearest integral value to a given floating-point value (although the result is still afloat). Thusround(3.8)evaluates to4.0. That result can subsequently be cast to anintif desired.

• The underlying integer encoding of a character is reported by the syntaxord(character), wherecharacteris a one-character string. Conversely, an integercodecan be converted to the corresponding one-character string using the syntaxchr(code).

Functions and Modules

• Some functions (e.g.,round) are defined outside the context of any particular class. We call these pure functions.

• Other common built-in functions includelen,sum,min, andmax.

• An enormous library of additional values, functions, and classes have been implemented by Python developers but not automatically included as built-ins. These additional tools are organized into modules that can be imported if desired.

• Importing and using a tool such as thesqrtfunction from themathmodule can be accom-plished in three styles.

>>> import math

>>> math.sqrt(2) 1.41421356237

>>> from math import sqrt

>>> sqrt(2) 1.41421356237

>>> from math import *

>>> sqrt(2) 1.41421356237 Expressions

• When multiple operations are expressed in a single statement, the Python interpreter eval-uates them one at a time.

• By default, Python dictates a set of precedence rules that are used to determine the order in which operations of a compound expression are performed.

• Certain operators are always given precedence over others, such as multiplication over addition.

• Operations of equal precedence are usually evaluated from left to right, although there are a few operators that are evaluated from right to left.

• A programmer can use parentheses to explicitly specify the order of evaluation.

• An evaluation tree can be used to diagram the order in which pieces of an expression are computed.

• Theboolclass is the simplest of all. It has only two instances,TrueandFalse. The class supports the expression of logical statements using operators such asnot,and, andor.

• Python syntax allows for compound expressions, including function calls, such as len(groceries) > 15 and'milk'in groceries.

Python Interpreter

• The Python interpreter can be started in one of three ways from a command line:

• python

starts a purely interactive session of the interpreter

• python sample.py

executes the code from a file, such as sample.py, ending the interpreter either when the program completes or when an error occurs.

• python -i sample.py

similar to previous, except rather than quitting the interpreter, it switches to interac-tive mode so that we can inspect the existing objects.

• Documentation for a class, function or other object can be accessed directly from the inter-preter by using the syntaxhelp(topic).

Using a file for source code

• Although we can experiment interactively in the interpreter, source code is usually written in a separate file, which can later be executed.

• Theprintcommand is used to generate output that will be visible to a user when executing a program.

• If multiple arguments are designated in aprintcommand, separated by commas, they are printed on the same line of output with a space between each pair.

• By default, a newline character is printed at the conclusion of eachprintstatement. How-ever, this newline is suppressed if a comma appears at the end of a print statement.

• Theraw_inputfunction can be used to get input from the user. A prompt for the user can be specified as an optional parameter. The return value is a string object containing the characters typed by the user in response.

• Comments can be added to a Python program following a#symbol. Those comments are ignored by the interpreter, and unseen by the user, but visible to programmers who review the source code.

2.11.2 Glossary

ASCII A standard ordering for an alphabet of 128 common characters, used for repre-senting text digitally.

assignment A statement that associates an identifier on the left-hand side of the= oper-ator with the object expressed on the right-hand side.

casting A conversion of data from one type to another.

comment An explanatory note in the source code that is ignored by the Python interpreter yet visible to a programmer.

constructor A special method that is implicitly called whenever an object is instantiated.

It is responsible for establishing the initial state of the object.

default parameter value Seeoptional parameter.

exclusive or Meeting one of two conditions but not both.

expression A single statement consisting of one or more operations.

identifier A name associated with some underlying object.

immutable The characteristic of an object whose state cannot be modified once con-structed.

inclusive or Meeting at least one of two conditions.

index An integer value used to identify a position in a sequential structure, such as a string or list. Indices are measured by the offset from the beginning, and thus the first position has index 0.

instantiation The construction of a new object in a given class.

left-associative Operators that are evaluated from left to right as part of an expression, as in18−5 + 2which is equivalent to(18−5) + 2.

list A built-in class used to manage a mutable sequence of elements.

literal An explicit value of an object drawn from one of the built-in classes.

module A library defining a combination of identifiers, functions and classes. Modules must be imported when needed.

mutable The characteristic of an object whose state can be changed by one or more of its methods.

operator A symbol (e.g.,+) that triggers a special behavior in Python.

optional parameter A parameter that can be sent to a function, yet which is assigned a default value if not sent.

parameter A piece of information sent from the caller to the callee upon invocation of a function.

polymorphism A technique in which objects of different types support a common syntax or when a single function supports multiple behaviors depending upon the type of parameter it receives.

precedence When one operation is performed before another in evaluating an expression.

Python defines strict rules for how precedence is determined.

pure function A function that is defined outside the context of any class.

Python interpreter The software that accepts and executes Python commands.

qualified name A syntax using “dot” notation (e.g., math.pi) for accessing a name defined in another context (such as a module).

slice A selected portion of a sequence, such as alist,str, ortuple, using a syntax such asdata[start:stop].

source code The characters that comprise commands for a program in a high-level lan-guage. Source code is typically stored in one or more text files and translated with an interpreter or compiler.

special method A method that provides implicit support for an alternative syntax in Python. For example, the _ _ add _ _method supports the+operator.

2.11.3 Exercises

In document OO Programming in Python (Page 94-100)