1. Trang chủ
  2. » Công Nghệ Thông Tin

Teach yourself python in 24 hours

686 131 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Contents

    • Ch1

    • Ch2

    • Ch3

    • Ch4

    • Ch5

    • Ch6

    • Ch7

    • Ch8

    • Ch9

    • Ch10

    • Ch11

    • Ch12

    • Ch13

    • Ch14

    • Ch15

    • Ch16

    • Ch17

    • Ch18

    • Ch19

    • Ch20

    • Ch21

    • Ch22

    • Ch23

    • Ch24

    • AppendixA

    • AppendixB

    • AppendixC

    • AppendixD

    • AppendixE

Nội dung

Sams Teach Yourself Python in 24 Hours Page i Sams Teach Yourself Python in 24 Hours Ivan Van Laningham Page ii Sams Teach Yourself Python in 24 Hours Copyright © 2000 by Sams Publishing All rights reserved No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher No patent liability is assumed with respect to the use of the information contained herein Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions Neither is any liability assumed for damages resulting from the use of the information contained herein International Standard Book Number: 0-672-31735-4 Library of Congress Catalog Card Number: 99-65588 Printed in the United States of America First Printing: April 2000 02 01 00 4321 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized Sams Publishing cannot attest to the accuracy of this information Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied The information provided is on an ''as is" basis AQUISITIONS EDITOR Scott D Meyers DEVELOPMENT EDITOR Scott D Meyers MANAGING EDITOR Charlotte Clapp PROJECT EDITOR George E Nedeff COPY EDITOR Barbara Hacha INDEXER Heather McNeill TECHNICAL EDITOR Aahz Maruch TEAM COORDINATOR Amy Patton MEDIA SPECIALIST Craig Atkins INTERIOR DESIGN Gary Adair COVER DESIGN Aren Howell COPYWRITER Eric Borgert LAYOUT TECHNICIANS Ayanna Lacey Heather Hiatt Miller Stacey Richwine-DeRome CONTENTS AT A GLANCE Part I Python Mind, Beginner's Mind What Is Python? The Python Interpreter 19 Basic Arithmetic with Python 31 Variables and Control Flow 51 Basic Data Types I: The Numeric Data Types 69 Basic Data Types II: The Sequence and Dictionary Data Types 83 Functions and Modules 111 Useful Miscellany 125 Part II Objects in Mirror Are Closer Than They Appear 145 Objects at Rest 147 10 Defining Objects 161 11 Object-Oriented Programming Concepts 175 12 More OOP Concepts 189 13 Special Class Methods in Python 203 14 The Laboratory of Dr Frankenstein 223 15 The Laboratory, Part II 239 16 Objects in Motion 251 Part III Introducing the Python GUI 283 17 Introducing the Python GUI 285 18 Tk Widgets I 297 19 Tk Widgets II 319 20 Tk Graphics I 335 21 Tk Graphics II 359 22 Tk Graphics III 381 23 The Mandelbrot Set 409 24 Miscellany 445 Part IV Appendixes 459 A Selected Bibliography 461 B Editors for Python 465 C Reserved Words and Identifiers in Python 469 D Special Class Methods in Python 475 E Other Python Resources 483 DEDICATION To my parents, Naomi and George, and their parents, Sarah, Leslie, Florence, and Leon, all of whom taught me that it is sometimes necessary to feed your hand to a tiger if you want to find out how the teethwork ACKNOWLEDGMENTS Some years ago, the artist Christo Javacheff ( http://www.artcyclopedia.com/artists/christo.html) built a work of art called ''Running Fence," a fence that ran from coast to coast across the United States Books are like this fence: connections among widely separated points in time and space This is why any attempt to thank everyone who contributed to this book is doomed to failure In some sense, this book was written by all the people I have ever known All I can is to single out a very few people for special mention Some who have been forgotten will know who they are, and are invited to email me so that I may set the record straight online Others may have no idea that they had anything to with this book, even though the absence of their contributions would have meant the absence of this book I would like to thank Fred Segovich and Peter Ahlsberg who in 1983 invited me to join a community of passionate eccentrics because they thought I would fit in They were right, and even though I left that community in 1990, the community has never left me I would like to thank Patrick E Kane and William Bradford Smith Pat said "sure" at exactly the right time and changed my life Bill helped me through my early, panicstricken, encounters with UNIX with his cheerful attitude and plain conviction that "it's just a bunch of bits, Ivan." I would also like to thank Bill, and the other members of the "Chanute Mafia," for his (and their) service to our country in a time of great trouble Keep 'em flying, Bill More directly, Pat helped by testing many of the programs in this book to make sure that they would run on his bizarre collection of hardware For stimulating conversation and dialogue about a wide range of subjects more or less related to this book, including Python, Mayan epigraphy, Zen Buddhism, Chinese snakes, split ergativity, and Vietnam, I would like to thank (in no particular order): Gordon McMillan, Tim Peters, Andrew M Kuchling, Guido van Rossum, Fredrik Lundh, David Ascher, Mark Minaga, Charles E Reed, Dan Bammes, Ellen Emerson White, Amy Page xiv ABOUT THE AUTHOR When there was a priesthood of computer operators, Ivan Van Laningham was a member; he helped create the Y2K problem In college, he was an anthropology major, acquiring a continuing interest in archaeology and archaeoastronomy He is now a software engineer for a voicemail company, but has also served in the Vietnam War, worked for the U.S Postal Service, been a joat for a mobile home park, obtained his forklift operator's license, lost his shirt as a luthier, and clerked in a bookstore where he worked for his future wife Since meeting UNIX in 1983 when hired as a hardware technician for a company later purchased by Motorola, he has been programming in C and C++ for a living (currently on Windows platforms) His other computer languages include 1401 Autocoder, COBOL, RPG, Sinclair Basic, PostScript, and Lisp He has been programming in X Windows since X11R2 His heart has been with Python since encountering Programming Python at the University of British Columbia bookstore Each year in March, he attends the Maya Meetings ( http://copan.bioz.unibas.ch/meso/infotexasmeet98.html) in Austin, Texas, a ten-day international conference and workshop on Mayan hieroglyphic writing Ivan works as a software engineer for Callware Technologies, Inc (http://www.callware.com), a voicemail company in Salt LakeCity Page xv Sedivy, Xuhua (Howard) Lin, Ying Wang, Duncan Steele, Simon Cassidy, Paul Hill, John Justeson, Lloyd B Anderson, Nicholas Hopkins, J Kathryn Josserand, Dave Beazley, Andy Robinson, Marilyn Knapp Litt (hi, LG!), Karen Offutt, Bobbie Keith, and the Fred formerly known as Fred I would also like to thank Xuhua (Howard) Lin, for the wonderful calligraphy, ''Python Mind, Beginner's Mind," which appears at the end of Hour 24 I would like to thank the author who anonymously posted the Klingon programming aphorisms to the Web I have adapted some of these aphorisms for use in Hour I would like to thank John Esser and Mike Hess for making Callware a better place to work than it has ever been before Aahz Maruch deserves special mention for serving as the technical editor for this book; without his astute and sharp-eyed commentary, there would have been many more errors here for the readers to find Thanks, Aahz: I knew you'd keep me honest Scott Meyers, my editor for this book, should be nominated for boddhisatva-hood (if there isn't any such word, there ought to be), due to the mass quantities of patience and forbearance he was required to bring to bear on this project Other members of the team at Sams deserve mention: Katie Robinson, Barbara Hacha, Gene Redding, Heather Mcneill, Amy Patton, George Nedeff, and all the others listed on the credits page Thank you all Despite their careful attentions, however, I am sure that errors remain A thousand years ago, the Mayans who built a great civilization in the jungles of Central America believed that mistakes in calendrical calculations were the fault not of the scribes or the astronomers, but were the result of direct intervention by the gods I believe this too If you find any errors in this book, please notify gods A through Z of the Mayan pantheon ( http://www.pauahtun.org/driveletter.html) I would like to thank Harley, Teddy Bear, and Trillin for reminding me of my real place in the scheme of things, and that cats come before Pythons, always It's hard to be depressed when someone short is patting your nose with a paw I would like to thank my wife, Audrey Thompson, for the love, interest, humor, charm, and insight she brings to my life I am every day more and more delighted to be part of the greatest conversation of all Page xvi TELL US WHAT YOU THINK! As the reader of this book, you are our most important critic and commentator We value your opinion and want to know what we're doing right, what we could better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way You can email or write me directly to let me know what you did or didn't like about this book—as well as what we can to make our books stronger Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message * Used in class-private name mangling; you won't really need this because it's a fairly advanced concept, but you can find out more about it at http://www.python.org/ Built-in Names The builtin module contains a minimum set of function names that you should never try to use, either as function names or variable names You can redefine them, but you won't like the results Redefining these names falls under the category of ''things that ought not to be done." The following is the full list Find out more at the usual place, http://www.python.org/ import () abs() apply() buffer() callable() chr() Page 473 cmp() coerce() compile() complex() delattr() dir() divmod() eval() execfile() filter() float() getattr() globals() hasattr() hash() hex() id() input() intern() int() isinstance() issubclass() len() list() locals() long() map() max() min() oct() open() ord() Page 474 pow() range() raw_input() reduce() reload() repr() round() setattr() slice() str() tuple() type() vars() xrange() Page 475 Appendix D Special Class Methods in Python Special class methods are an important feature of Python, making it an extremely flexible language All user-defined classes may provide implementations of these methods, which are called or invoked whenever the appropriate action is called for by the Python interpreter You'll find detailed discussion of all these methods in Chapter 13, ''Special Class Methods in Python." What is listed here is intended only to jog your memory, not to provide a detailed explanation Therefore, the methods are listed here in alphabetical order A listing by use can be found at the official Python Reference Manual: http://www.python.org/doc/current/ref/index.html, Section 3.3 Each explanation is preceded by the general use of the method Note that in the following methods, when it says "return the result" or something like that, you need to create a new object to return For instance, x = x + y uses x and y as inputs but creates a whole new object to return, which is assigned to x after the calculation is performed Page 476 abs (self) Numeric; return the absolute value of self (no sign) add (self,other) Numeric and sequence; add self to other or concatenate self and other, and return the result and (self,other) Numeric; return the result of bitwise and'ing (&) self with other call (self[,args]) Class; if it makes sense to treat your class as a function, implement this method; args are optional cmp (self,other) Class, others; called by all comparison operations Return -1 if self is < other, if self and other are equal, and if self is > than other coerce (self,other) Numeric; called whenever self and other must be converted to a common type for some sort of arithmetic operation Usually, you convert other to an instance of your class, although you could convert your class to whatever type other is Return a tuple: (self,other) complex (self) Numeric; if your class can be converted to a complex number, return that complex equivalent del (self) Class; called when an instance of your class is about to be destroyed Lots of gotchas; see Chapter 13 for details delattr (self,name) Access; called when del object.name is called delitem (self,key) Sequence and mapping; called when del object[key] is called delslice (self,i,j) Sequence and mapping; called when del object[i:j] is called Page 477 div (self,other) Numeric; divide self by other and return the result divmod (self,other) Numeric; divide self by other and return a tuple of the result and the remainder float (self) Numeric; if your class can be converted to a floating point number, return that floating point equivalent getattr (self,name) Access; called only if object.attribute lookup fails Return the value of attribute or raise AttributeError getitem (self,key) Sequence and mapping; called when a call to object[key] is made Keys are usually integers; negative index implementation must be done in this method if your class supports it getslice (self,i,j) Sequence and mapping; called when a call to object[i:j] is made Both i and j are integers; negative index implementation is up to this method hash (self) Class; return a 32-bit value that can be used as a hash index Called by using your class object as a key for a dictionary and by the built-in hash() function If your class is mutable, not implement the hash method hex (self) Numeric; return a string representing the hexadecimal equivalent of your class init (self[,args]) Class; called when an instance of your class is created The args optional int (self) Numeric; if your class can be converted to an integer, return that integer equivalent invert (self) Numeric; return the result of a bitwise invert operation (~) Page 478 len (self) Sequence and mapping; called by built-in function len() Return the length of your class, however you want to define it long (self) Numeric; if your class can be converted to a long integer, return that long integer equivalent lshift (self,other) Numeric; return the result of performing a left-shift (

Ngày đăng: 12/09/2017, 01:51

TỪ KHÓA LIÊN QUAN