python 简明教程


综述

根据SICP,一门语言有以下模式:

  • primitive expressions, which represent the simplest entities the
    language is concerned with,

  • means of combination, by which compound elements are built
    from simpler ones, and

  • means of abstraction, by which compound elements can be named
    and manipulated as units.

在Python中,可以分为Lexical Analysis对应抽象方法(程序的骨架)、Data Model与Execution Model对应元标识符(程序的数据结构)、其他对应程序的算法。唯有Lexical Analysis是Python的特质。这里是Python的核心内容。这篇文章会夹杂一些文字,但是一定点到为止。

Lexical Analysis

A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer.

Line Structure

Python使用行结构

Class And Object

“被命名的类,称之为对象,对象因此与其他对象不同。”———qianxin

Scope

在Python中,名字和对象是绑定起来的,而不是Copy.
Python与其他语言最大不同之处在于Python没有private, protected, public,而只有local, nonlocal, global。python中nonlocal的功能是使用外层(而非内部的)变量
The global statement can be used to indicate that particular variables live in the global scope and should be rebound there; the nonlocal statement indicates that particular variables live in an enclosing scope and should be rebound there.
nonlocal为python3特有

def scope_test():
      def do_local():
            spam = "local spam"
      def do_nonlocal():
            //not "local spam"
            nonlocal spam
            spam = "nonlocal spam"
      def do_global():
            global spam
            spam = "global spam"

spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)

output:

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

Class Objects

class Complex():
      flag = "Complex"
      def __init__(self, realpart, imagpart):
            self.r = realpart
            self.i = imagpart

c = Complex(5.0,3.0)
d = Complex(4.2,1.5)
c.r,c.i
c.flag,d.flag
(5.0,3.0)
('Complex','Complex')

Data Structure

List[]

count(),index(),reverse().

 fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

List(Stack)

append(), pop()

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

List(Queue)

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")
 # Terry arrives
>>> queue.append("Graham")
 # Graham arrives
>>> queue.popleft()
 # The first to arrive now leaves
'Eric'
>>> queue.popleft()
 # The second to arrive now leaves
'John'
>>> queue
 # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

List(Range() ,listcomp,del statement)

for x in [1,2,3]:
        ...
        for y in [3,1,4]:
              ...
              if x != y:
                     (x,y)
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
a = [i for i in range(10)]
del a[5:]
a
[0,1,2,3,4]

Tuple(Real Sequence)()

广义表数据类型,不限制原子类型

t = 12345, 54321, 'hello!'
t
u = t, (1,2,3,4,5)
u
# Error! Imutable! 
# t[0] = 88888

# But can contain mutable objects:
v = ([1,2,3], [4,5,6])
v[0][1] = 88888
v
(12345, 54321, 'hello!')
((12345, 54321, 'hello!'),(1,2,3,4,5))
([1,88888,3],[4,5,6])

Singleton和Tuple Packing

empty = ()
singleton = 'hello',
len(empty)
len(singleton)
singleton

x,y,z = t
x
y
z
0
1
('hello',)
12345
54321
'hello!'

Set{}

A set is an unordered collection with no duplicate elements.

set(), in()

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
 # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket
True
>>> 'crabgrass' in basket
False
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b
 # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b
 # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
a = {x for x in 'abracadabra' if x not in 'abc'}

Dictionaries{x:y}

可以给值赋值,不能改键值(Set不能改元素)
del statement, in,
list()返回List类型,
sorted()返回排序后的List

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}