2011年12月30日 星期五

[Quick Python] 3. The Quick Python overview

 以下內容來自 "The Quick Python Book" : 
 
Preface : 
The purpose of this chapter is to give you a basic feeling for the syntax, semantics, capabilities, and philosophy of the Python language. It has been designed to provide you with an initial perspective or conceptual framework on which you'll be able to add details as you encounter them in the rest of the book. 

On an initial read read, you needn't be concerned about working through and understanding the details of the code segments. You'll be doing fine if you pick up a bit of an idea about what is being done. The subsequent chapters of this book will walk you through the specifics of these features and won't assume prior knowledge. You can always return to this chapter and work though the examples in the appropriate sections as review after you've red the later chapters. 

Python synopsis : 
Python has a number of built-in data types such as integers, floats, complex numbers, strings, lists, tuples, dictionaries and file objects. These can be manipulated using language operators, built-in functions, library functions, or a data type' sown methods. 

Programmers can also define their own classes and instantiate their own class instances. These can be manipulated by programmer-defined methods as well as the language operators and built-in functions for which the programmer has defined the appropriate special method attributes. Python provides conditional and iterative control flow through an if-elif-else construct along with while and for loops. It allows function definition with flexible argument-passing options. Exceptions (error) can be raised using the raise statement and caught and handled using the try-except-else construct. 

Variables don't have to be declared and can have any built-in data type, user-defined object, function, or module assigned to them. 

Built-in data types 
Python has several built-in data types, from scalars like numbers and Booleans, to more complex structures like lists, dictionaries and files. 
- Numbers 
Python's four number types are integers, floats, complex numbers and Booleans : 
* Integer - 1, -3, 42, 355, 88888888, -7777
* Floats - 3.0, 31e12, -6e-4
* Complex numbers - 3+2j, -4-2j, 4.2+6.3j
* Booleans - True, False

You can manipulate them using the arithmetic operators : +(addition), -(subtraction), *(multiplication), /(division), **(exponentiation), and %(modulus). The following examples use integers : 
 

Division of integers with / (1) results in a float (new in Python 3.x), and division of integers with // (2) results in truncation. Note that integers are of unlimited size(3), they will grow as large as you need them to. These examples work with floats, which are based on the doubles in C. Next, the following examples use complex numbers : 
 

Complex numbers consists of both a real element and an imaginary element, suffixed with a j. In the preceding code, variable x is assigned to a complex number. You can obtain its "real" part using the attribute notation x.real
Several built-in functions can operate on numbers. There are also the library module cmath (which contains functions for complex numbers) and the library module math(which contains functions for the other three types) : 
 

Built-in functions are always available and are called using a standard function calling syntax. In the preceding code, round() is called with a float as its input argument. The functions in library modules are made available using the import statement. At (2), the math library module is imported, and its cell() function is called using attribute notation : module.function(arguments)

The following examples use Booleans : 
 

Other than their representation as True and False, Booleans behave like the number 1 (True) and 0 (False). 

- Lists 
Python has a powerful built-in list type : 
[]
[1]
[1, 2, 3, 4, 5]
[1, "two", 3L, 4.0, ["a", "b"], (5,6)] <---(1)

A list can contain a mixture of other types as its elements, including strings, tuples, lists, dictionaries, functions, file objects and any type of number (1). A list can be indexed from its front or back. You can also refer to a subsegment, or slice, of a list using slice notation : 
 

Obtain a slice using [m:n] (3), where m is the inclusive starting point and n is the exclusive ending point. An [:n] slice (4) starts at its beginning, and an [m:] slice goes to a list's end. You can use this notation to add, remove, and replace elements in a list or to obtain an element or a new list that is a slice from it : 
 

Some built-in functions (lenmax and min), some operators (in+, and *), the del statement, and the list methods (appendcountextendindexinsertpopremove,reverse, and sort) will operate on lists : 
 

The operators + and * each create a new list, leaving the original unchanged (1). A list's methods are called using attribute notation on the list itself :x.method(arguments)

- Tuples 
Tuples are similar to lists but are immutable - that is, they can't be modified after they have been created. The operators (in+ and *) and built-in functions (lenmax, andmin), operate on them the same way as they do on lists, because none of them modify the original. Index and slice notation work the same way for obtaining elements or slices but can't be used to add, remove or replace elements. There are also only two tuple methods : count() and index()A major purpose of tuples is for use as keys for dictionaries. They're also more efficient to use when you don't need modification. 
()
(1,) <--- (1)
(1, 2, 3, 4, 5)
(1, "two", 3L, 4.0, ["a","b"], (5, 6)) <--- (2)

A one-element tuple (1) needs a comma. A tuple, like a list, can contain a mixture of other types as its elements (2). A list can be converted to a tuple using the bulit-in function tuple() : 
>>> x = [1, 2, 3, 4]
>>> tuple(x)
(1, 2, 3, 4)

Conversely, a tuple can be converted to a list using the built0in function list() : 
>>> x = (1, 2, 3, 4)
>>> list(x)
[1, 2, 3, 4]

- Strings 
String processing is one of Python's strengths. There are many options for delimiting strings : 
"A string in double quotes can obtain 'single quote' characters."
'A string in single quotes can obtain "double quote" characters.'
'''\This string starts with a tab and ends with a newline character.\n'''
"""This is a triple double quoted string, the only kind that can contain real newlines."""

String can be delimited by singe (' '), double (" "), triple single (''' '''), or triple double (""" """) quotations and can contain tab(\t) and newline (\n) characters. Strings are also immutable. The operators and functions that work with them return new strings derived from the original. The operators (in+, and *) and built-in functions (lenmaxand min) operate on strings as they do on lists and tuples. Index and slice notation works the same for obtaining elements or slices but can't be used to add, remove, or replace elements. Strings have several methods to work with their contents, and the re library module also contains functions for working with strings : 
 

The print() function output strings. Other python data types can be easily converted to strings and formatted : 
 

- Dictionaries 
Python's built-in dictionary data type provides associate array functionality implemented using hash tables. The built-in len() function returns the number of key-value pairs in a dictionary. The del statement can be used to delete a key-value pair. As is the case for lists, a number of dictionary methods (clearcopygethas_keyitemskeys,update and values) are available : 
 

Keys must be of an immutable type (1). This includes numbers, strings and tuple. Values can be any kind of object. The dictionary method get() optionally returns a user-definable value when a key isn't in the dictionary. 

- Set 
A set in Python is an unordered collection of objects, used in situations where membership and uniqueness in the set are the main things you need to know about that object. You can think of sets as a collection of dictionary keys without any associated values : 
 

You can create a set by using set() on a sequence, like a list (1). When a sequence is made into a set, duplicates are removed (2). The in keyword (3) is used to check for membership of an object in a set. 

- File objects 
A file is accessed through a Python file object : 
 

The open statement (1) creates a file object. Here the file myfile in the current working directory is being opened in write ("w") mode. After writing two lines to it and closing it (2), we open the same file again, this time in the read ("r") mode. The os module provides a number of functions for moving around the file system and working with the pathnames of files and directories. Here, we move to another directory (4). But by referring to the file by an absolute path name, we are still able to access it. 
A number of other input/output capabilities are available. You can use the built-in input function to prompt and obtain a string from the user. The sys library module allows access to stdin, stdout, and stderr. The struct library module provides support for reading and writing files that were generated by or are to be used by C programs. ThePickle library module delivers data persistence through the ability to easily read and write the Python data types to and from files. 

Control flow structures : 
Python has a full range of structures to control code execution and program flow, including common branching and looping structures. 

- Boolean values and expressions 
Python has several ways of expressing Boolean values; the Boolean constant False, 0, the Python nil value None, and empty values (for example, the empty list [ ] or empty string ""are all taken as False. The Boolean constant True and everything else are considered True. You can create comparison expressions using the comparison operators (<, <=, ==, >, >=, !=, is, is not, in, not in) and the logical operators (and, not, or), which all return True or False. 

- The if-elif-else statement 
The block of code after the first true condition (of an if or an elif) is executed. If none of the conditions is true, the block of code after the else is executed : 
 

The elif and else clauses are optional, and there can be any number of elif clauses. Python uses indentation to delimit blocks. No explicit delimiters such as brackets or braces are necessary. Each block consists of one or more statements separated by newlines. These statements must all be at the same level of indentation. 

- The while loop 
The while loop is executed as long as the condition (which here is x > y) is true : 
 

First line is a shorthand notation. Here, u and v are assigned a value of 0, x is set to 100, and y obtains a value of 30. After while statement is the loop block. It’s possible for it to contain break (which ends the loop) and continue statements (which abort the current iteration of the loop). 

- The for loop 
The for loop is simple but powerful because it’s possible to iterate over any iterable type, such as a list or tuple. Unlike in many languages, Python’s for loop iterates over each of the items in a sequence, making it more of a foreach loop. The following loop finds the first occurrence of an integer that is divisible by 7: 
 

x is sequentially assigned each value in the list (1). If x isn’t an integer, then the rest of this iteration is aborted by the continue statement (2). Flow control continues with x set to the next item from the list. After the first appropriate integer is found, the loop is ended by the break statement (3). 

- Function definition 
Python provides flexible mechanisms for passing arguments to functions : 
 

Functions are defined using the def statement (1). The return statement (2) is what a function uses to return a value. This value can be of any type. If no return statement is encountered, Python’s None value is returned. Function arguments can be entered either by position or by name (keyword). Here z and y are entered by name (3). Function parameters can be defined with defaults that are used if a function call leaves them out (4). A special parameter can be defined that will collect all extra positional arguments in a function call into a tuple (5). Likewise, a special parameter can be defined that will collect all extra keyword arguments in a function call into a dictionary (6). 

- Exceptions 
Exceptions (errors) can be caught and handled using the try-except-finally-else compound statement. This statement can also catch and handle exceptions you define and raise yourself. Any exception that isn’t caught will cause the program to exit. Below shows basic exception handling : 
 

Here we define our own exception type inheriting from the base Exception type (1). If an IOError or EmptyFileError occurs during the execution of the statements in thetry block, the associated except block is executed (2). This is where an IOError might be raised (3). Here we raise the EmptyFileError (4). The else clause is optional (5). It’s executed if no exception occurs in the try block (note that in this example, continue statements in the except blocks could have been used instead). The finally clause is optional (6). It’s executed at the end of the block whether an exception was raised or not. 

Module creation : 
It’s easy to create your own modules, which can be imported and used in the same way as Python’s built-in library modules. The example below is a simple module with one function that prompts the user to enter a filename and determines the number of times words occur in this file : 
- wo.py :
  1. """wo module. Contains function: words_occur()"""  
  2. interface functions  
  3. def words_occur():  
  4.     """words_occur() - count the occurences of words in a file."""  
  5.     # Prompt user for the name of the file to use. (1)  
  6.     file_name = input("Enter the name of the file: ")  
  7.     # Open the file, read it and store its words in a list.  
  8.     f = open(file_name, 'r')  
  9.     word_list = f.read().split() # (2)  
  10.     f.close()  
  11.     # Count the number of occurences of each word in the file.  
  12.     occurs_dict = {}  
  13.     for word in word_list:  
  14.         # increment the occurences count for this word  
  15.         occurs_dict[word] = occurs_dict.get(word, 0) + 1  
  16.     # Print out the results. (3)  
  17.     print("File %s has %d words (%d are unique)" \  
  18.           % (file_name, len(word_list), len(occurs_dict)))  
  19.     print(occurs_dict)  
  20.   
  21. #(4)  
  22. if __name__ == '__main__':   
  23.     words_occur()  

Comments are anything beginning with a # character (1). read() returns a string containing all the characters in a file (2), and split() returns a list of the words of a string "split out" based on whitespace. You can use a \ to break a long statement across multiple lines (3). This allows the program to also be run as a script by typing python wo.py at a command line (4). 
If you place a file in one of the directories on the module search path, which can be found in sys.path, then it can be imported like any of the built-in library modules using the import statement : 
>>> import wo
>>> wo.words_occur()
Enter the name of the file:

If you change the file wo.py on disk, import won’t bring changes in to the same interactive session. You use the reload() function from the imp library in this situation : 
>>> import imp
>>> imp.reload(wo)
wo' from 'wo.py'>

For larger projects, there is a generalization of the module concept called packages. This allows you to easily group a number of modules together in a directory or directory subtree and import and hierarchically refer to them using a package.subpackage. module syntax. This entails little more than the creation of a possibly empty initialization file for each package or subpackage. 

Object-oriented programming : 
Python provides full support for OOP. Below is an simple example that might be the start of a simple shapes module for a drawing program : 
- sh.py :
  1. """sh module. Contains classes Shape, Square and Circle"""  
  2. class Shape: # (1)  
  3.     """Shape class: Has method move"""  
  4.     def __init__(self, x, y):  # (2)  
  5.         self.x = x  # (3)  
  6.         self.y = y  
  7.     def move(self, deltaX, deltaY):   # (4)  
  8.         self.x = self.x + deltaX  
  9.         self.y = self.y + deltaY  
  10.   
  11. class Square(Shape):  
  12.     """Square class: Inherits from Shape"""  
  13.     def __init__(self, side=1, x=0, y=0):  
  14.         Shape.__init__(self, x, y)  
  15.         self.side = side  
  16.   
  17. class Circle(Shape): # (5)  
  18.     """Circle class: Inherits from Shape and has method area"""  
  19.     pi = 3.14159  # (6)  
  20.     def __init__(self, r=1, x=0, y=0):  
  21.         Shape.__init__(self, x, y)  # (7)  
  22.         self.radius = r  
  23.     def area(self):  
  24.         """Circle area method: Returns the area of the circle."""  
  25.         return self.radius * self.radius * self.pi  
  26.     def __str__(self):  # (8)  
  27.         return "Circle of radius %s at coordinates (%d, %d)" \  
  28.                % (self.radius, self.x, self.y)  

Classes are defined using the class keyword (1). The instance initializer method (constructor) for a class is always called __init__ (2). Instance variables x and y are created and initialized here (3). Methods, like functions, are defined using the def keyword (4). The first argument of any method is by convention called self. When the method is invoked, self is set to the instance that invoked the method. Class Circle inherits from class Shape (5). This is similar to but not exactly like a standard class variable (6). A class must, in its initializer, explicitly call the initializer of its base class (7). The __str__ method is used by the print function (8). Other special attribute methods permit operator overloading or are employed by built-in methods such as the length (len) function. 

Importing this file makes these classes available : 
 

The initializer is implicitly called, and a circle instance is created (1). The print function implicitly uses the special __str__ method (2). Here we see that the move method of Circle’s parent class Shape is available (3). A method is called using attribute syntax on the object instance: object.method(). The first (self) parameter is set implicitly.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...