• No results found

Thinking About Objects: Introduction to Object Technology

In document Python - How to Program (Page 61-68)

Introduction to Python Programming

Line 4 creates a string with the familiar double-quote character (") If we want such a string to print double quotes to the screen, we must use the escape sequence for the double-

2.10 Thinking About Objects: Introduction to Object Technology

In each of the first six chapters, we concentrate on the “conventional” methodology of structured programming, because the objects we will build will be composed in part of structured-program pieces. Now we begin our early introduction to object orientation. In this section, we will see that object orientation is a natural way of thinking about the world and of writing computer programs.

We begin our introduction to object orientation with some key concepts and termi- nology. First, look around you in the real world. Everywhere you look you see them— objects!—people, animals, plants, cars, planes, buildings, computers, etc. Humans think in terms of objects. We have the marvelous ability of abstraction that enables us to view 12 # read second string and convert to integer

13 number2 = raw_input( "Please enter second integer: " ) 14 number2 = int( number2 )

15

16 if number1 == number2:

17 print "%d is equal to %d" % ( number1, number2 ) 18

19 # improper indentation causes this if statement to execute only 20 # when the above if statement executes

21 if number1 != number2:

22 print "%d is not equal to %d" % ( number1, number2 ) 23

24 if number1 < number2:

25 print "%d is less than %d" % ( number1, number2 ) 26

27 if number1 > number2:

28 print "%d is greater than %d" % ( number1, number2 ) 29

30 if number1 <= number2:

31 print "%d is less than or equal to %d" % ( number1, number2 ) 32

33 if number1 >= number2:

34 print "%d is greater than or equal to %d" % ( number1, number2 )

Enter two integers, and I will tell you the relationships they satisfy.

Please enter first integer: 1 Please enter second integer: 2 1 is less than 2

1 is less than or equal to 2

Fig. 2.25 Fig. 2.25 Fig. 2.25

images on a computer screen as objects such as people, planes, trees and mountains, rather than as individual dots of color. We can, if we wish, think in terms of beaches rather than grains of sand, forests rather than trees and buildings rather than bricks.

We might be inclined to divide objects into two categories—animate objects and inan- imate objects. Animate objects are “alive” in some sense. They move around and do things. Inanimate objects, like towels, seem not to do much at all. They just “sit around.” All these objects, however, do have some things in common. They all have attributes, like size, shape, color and weight, and they all exhibit behaviors (e.g., a ball rolls, bounces, inflates and deflates; a baby cries, sleeps, crawls, walks and blinks; a car accelerates, brakes and turns; a towel absorbs water).

Humans learn about objects by studying their attributes and observing their behaviors. Different objects can have similar attributes and can exhibit similar behaviors. Compari- sons can be made, for example, between babies and adults and between humans and chim- panzees. Cars, trucks, little red wagons and roller skates have much in common.

Object-oriented programming (OOP) models real-world objects using software coun- terparts. It takes advantage of class relationships, where objects of a certain class—such as a class of vehicles—have the same characteristics. It takes advantage of inheritance rela- tionships, and even multiple inheritance relationships, where newly created classes of objects are derived by absorbing characteristics of existing classes and adding unique char- acteristics of their own. An object of class “convertible” certainly has the characteristics of the more general class “automobile,” but a convertible’s roof goes up and down.

Object-oriented programming gives us a more natural and intuitive way to view the programming process, by modeling real-world objects, their attributes and their behaviors. OOP also models communications between objects. Just as people send messages to one another (e.g., a sergeant commanding a soldier to stand at attention), objects communicate via messages.

OOP encapsulates data (attributes) and functions (behavior) into packages called objects; the data and functions of an object are intimately tied together. Objects have the property of information hiding. This means that, although objects may know how to com- municate with one another, objects normally are not allowed to know how other objects are implemented—implementation details are hidden within the objects themselves. Surely it is possible to drive a car effectively without knowing the details of how engines, transmis- sions and exhaust systems work internally. We will see why information hiding is so crucial to good software engineering.

In C and other procedural programming languages, programming tends to be action- oriented; in Python, programming is object-oriented (ideally). The function is the unit of programming in procedural programming. In object-oriented programming, the unit of pro- gramming is the class from which objects are eventually instantiated (a fancy term for “cre- ated”). Python classes contain functions (that implement class behaviors) and data (that implements class attributes).

Procedural programmers concentrate on writing functions. Groups of actions that per- form some task are formed into functions, and functions are grouped to form programs. Data is certainly important in procedural programming, but the view is that data exists pri- marily in support of the actions that functions perform. The verbs in a system specification help the procedural programmer determine the set of functions that will work together to implement the system.

Object-oriented programmers concentrate on creating their own user-defined types called classes. Each class contains both data and the set of functions that manipulate the data. The data components of a class are called data members or attributes. The functional components of a class are called methods (or member functions in other object-oriented lan- guages). The focus of attention in object-oriented programming is on classes rather than functions. The nouns in a system specification help the object-oriented programmer deter- mine the set of classes that will be used to create the instances that will work together to implement the system.

Classes are to objects as blueprints are to houses. We can build many houses from one blueprint, and we can create many objects from one class. Classes can also have relation- ships with other classes. For example, in an object-oriented design of a bank, the Bank-

Teller class needs to relate to the Customer class. These relationships are called associations.

We will see that, when software is packaged as classes, these classes can be reused in future software systems. Groups of related classes are often packaged as reusable compo- nents or modules. Just as real-estate brokers tell their clients that the three most important factors affecting the price of real estate are “location, location and location,” we believe the three most important factors affecting the future of software development are “reuse, reuse and reuse.”

Indeed, with object technology, we will build most future software by combining “stan- dardized, interchangeable parts” called components. This book will teach you how to “craft valuable classes” for reuse, reuse and reuse. Each new class you create will have the potential to become a valuable software asset that you and other programmers can use to speed and enhance the quality of future software-development efforts. This is an exciting possibility.

In this chapter, we have introduced many important features of Python, including printing data on the screen, inputting data from the keyboard, performing calculations and making decisions. In Chapter 3, Control Structures, we build on these techniques as we introduce structured programming. We will study how to specify and vary the order in which statements are executed—this order is called flow of control. Also, we introduced the basic concepts and terminology of object orientation. In Chapters 7–9, we expand our dis- cussion on object-oriented programming.

SUMMARY

• Programmers insert comments to document programs and to improve program readability. Com- ments also help other programmers read and understand your program. In Python, comments are denoted by the pound symbol (#).

• A comment that begins with # is called a single-line comment, because the comment terminates at the end of the current line.

• Comments do not cause the computer to perform any action when the program is run. Python ig- nores comments.

• Programmers use blank lines and space characters to make programs easier to read. Together, blank lines, space characters and tab characters are known as white space. (Space characters and tabs are known specifically as white-space characters.)

• Blank lines are ignored by Python.

• The standard output stream is the channel by which information presented to the user by an appli- cation—this information typically is displayed on the screen, but may be printed on a printer, writ-

ten to a file, etc. It may even be spoken or issued to braille devices, so users with visual impairments can receive the outputs.

• The print statement instructs the computer to display the string of characters contained between the quotation marks. A string is a Python data type that contains a sequence of characters. • A print statement normally sends a newline character to the screen. After a newline character is

sent, the next string displayed on the screen appears on the line below the previous string. Howev- er, a comma (,) tells Python not to send the newline character to the screen. Instead, Python adds a space after the string, and the next string printed to the screen appears on the same line. • Output (i.e., displaying information) and input (i.e., receiving information) in Python are accom-

plished with streams of characters.

• Python files typically end with .py, although other extensions (e.g., .pyw on Windows) can be used.

• When the Python interpreter executes a program, the interpreter starts at the first line of the file and executes statements until the end of the file.

• The backslash (\) is an escape character. It indicates that a “special” character is to be output. When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence.

• The escape sequence \n means newline. Each occurrence of a \n (newline) escape sequence caus- es the screen cursor to position to the beginning of the next line.

• A built-in function is a piece of code provided by Python that performs a task. The task is per- formed when the function is invoked or called. After performing its task, a function may return a value that represents the end result of the task.

• In Python, variables are more specifically referred to as objects. An object resides in the comput- er’s memory and contains information used by the program. The term object normally implies that attributes (data) and behaviors (methods) are associated with the object. The object’s methods use the attributes to perform tasks.

• A variable name consists of letters, digits and underscores (_) and does not begin with a digit. • Python is case sensitive—uppercase and lowercase letters are different, so a1 and A1 are different

variables.

• An object can have multiple names, called identifiers. Each identifier (or variable name) referenc- es (points to) the object (or variable) in memory.

• Each object has a type. An object’s type identifies the kind of information (e.g., integer, string, etc.) stored in the object.

• In Python, every object has a type, a size, a value and a location.

• Function type returns the type of an object. Function id returns a number that represents the ob- ject’s location.

• In languages like C++ and Java, the programmer must declare the object type before using the ob- ject in the program. In Python, the type of an object is determined automatically, as the program executes. This approach is called dynamic typing.

• Binary operators take two operands. Examples of binary operators are + and -.

• Starting with Python version 2.2, the behavior of the / division operator will change from “floor division” to “true division.”

• Floor division (sometimes called integer division), divides the numerator by the denominator and returns the highest integer value that is not greater than the result. Any fractional part in floor di- vision is simply discarded (i.e., truncated)—no rounding occurs.

• True division yields the precise floating-point result of dividing the numerator by the denominator. • The behavior (i.e., floor or true division) of the / operator is determined by the type of the oper- ands. If the operands are both integers, the operator performs floor division. If one or both of the operands are floating-point numbers, the operator perform true division.

• The // operator performs floor division.

• Programmers can change the behavior of the / operator to perform true division with the statement

from __future__ import division.

• In Python version 3.0, the only behavior of the / operator will be true division. After the release of version 3.0, all programs are expected to have been updated to compensate for the new be- havior.

• Python provides the modulus operator (%), which yields the remainder after integer division. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. This operator is most commonly used with integer operands, but also can be used with other arithmetic types.

• The modulus operator can be used with both integer and floating-point numbers.

• Arithmetic expressions in Python must be entered into the computer in straight-line form. Thus, expressions such as “a divided by b” must be written as a / b, so that all constants, variables and operators appear in a straight line.

• Parentheses are used in Python expressions in much the same manner as in algebraic expressions. For example, to multiply a times the quantity b + c, we write a * (b + c).

• Python applies operators in arithmetic expressions in a precise sequence determined by the rules of operator precedence, which are generally the same as those followed in algebra.

• When we say that certain operators are applied from left to right, we are referring to the associa- tivity of the operators.

• Python provides strings as a built-in data type and can perform powerful text-based operations. • Strings can be created using the single-quote (') and double-quote characters ("). Python also sup-

ports triple-quoted strings. Triple-quoted strings are useful for programs that output strings with quote characters or large blocks of text. Single- or double-quote characters inside a triple-quoted string do not need to use the escape sequence, and triple-quoted strings can span multiple lines. • A field width is the minimum size of a field in which a value is printed. If the field width is larger

than that needed by the value being printed, the data normally is right-justified within the field. To use field widths, place an integer representing the field width between the percent sign and the con- version-specifier symbol.

• Precision has different meaning for different data types. When used with integer conversion spec- ifiers, precision indicates the minimum number of digits to be printed. If the printed value contains fewer digits than the specified precision, zeros are prefixed to the printed value until the total num- ber of digits is equivalent to the precision.

• When used with a floating-point conversion specifier, the precision is the number of digits to ap- pear to the right of the decimal point.

• When used with a string-conversion specifier, the precision is the maximum number of characters to be written from the string.

• Exponential notation is the computer equivalent of scientific notation used in mathematics. For ex- ample, the value 150.4582 is represented in scientific notation as 1.504582 X 102 and is rep- resented in exponential notation as 1.504582E+002 by the computer. This notation indicates that 1.504582 is multiplied by 10 raised to the second power (E+002). The E stands for “ex- ponent.”

• An if structure allows a program to make a decision based on the truth or falsity of a condition. If the condition is true, (i.e., the condition is met), the statement in the body of the if structure is executed. If the condition is not met, the body statement is not executed.

• Conditions in if structures can be formed with equality relational operators. The relational oper- ators all have the same level of precedence and associate from left to right. The equality operators both have the same level of precedence, which is lower than the precedence of the relational op- erators. The equality operators also associate from left to right.

• Each if structure consists of the word if, the condition to be tested and a colon (:). An if struc- ture also contains a body (called a suite).

• Python uses indentation to delimit (distinguish) sections of code. Other programming languages often use braces to delimit sections of code. A suite is a section of code that corresponds to the body of a control structure. We study blocks in the next chapter.

• The Python programmer chooses the number of spaces to indent a suite or block, and the number of spaces must remain consistent for each statement in the suite or block.

• Splitting a statement over two lines can also cause a syntax error. If a statement is long, the state- ment can be spread over multiple lines using the \ line-continuation character.

• Object-oriented programming (OOP) models real-world objects with software counterparts. It takes advantage of class relationships where objects of a certain class—such as a class of vehi- cles—have the same characteristics.

• OOP takes advantage of inheritance relationships, and even multiple-inheritance relationships, where newly created classes of objects are derived by absorbing characteristics of existing classes and adding unique characteristics of their own.

• Object-oriented programming gives us a more natural and intuitive way to view the programming process, namely, by modeling real-world objects, their attributes and their behaviors. OOP also models communication between objects.

• OOP encapsulates data (attributes) and functions (behavior) into packages called objects; the data and functions of an object are intimately tied together.

• Objects have the property of information hiding. Although objects may know how to communicate with one another across well-defined interfaces, objects normally are not allowed to know how other objects are implemented—implementation details are hidden within the objects themselves. • In Python, programming can be object-oriented. In object-oriented programming, the unit of pro- gramming is the class from which instances are eventually created. Python classes contain meth- ods (that implement class behaviors) and data (that implements class attributes).

• Object-oriented programmers create their own user-defined types called classes and components. Each class contains both data and the set of functions that manipulate the data. The data compo- nents of a class are called data members or attributes.

• The functional components of a class are called methods (or member functions, in some other ob- ject-oriented languages).

• The focus of attention in object-oriented programming is on classes rather than on functions. The nouns in a system specification help the object-oriented programmer determine the set of classes that will be used to create the instances that will work together to implement the system.

TERMINOLOGY

abstraction arithmetic operator

alert escape sequence (\a) assignment statement

association memory location

associativity method

associativity of operators modeling

asterisk (*) modulus

attribute modulus operator (%)

backslash (\) escape sequence multiple inheritance

backspace (\b) newline character (\n)

behavior object

binary operator object orientation

block OOP (object-oriented programming)

built-in function operand

calculation operator overloading

calling a function operator precedence

carriage return (\r) overloading

case sensitive percent sign (%)

class polynomial

comma-separated list precedence

comment precision

component procedural programming language

condition pseudocode

conversion specifier .py extension

data member .pyw extension

debugging raw_input function

design readability

dynamic typing redundant parentheses

embedded parentheses relational operator

encapsulation reused class

equality operators right justify

escape character scientific notation

escape sequence screen output

execute second-degree polynomial

exponential notation self-documentation

exponentiation single-line comment

In document Python - How to Program (Page 61-68)