Assignments-Learning Python Chapter 11

来源:互联网 发布:黎巴嫩真主党 知乎 编辑:程序博客网 时间:2024/05/22 08:02

1. Assignment statement:

Target of an assignment on the left, and object to be assigned on the right.

1) Assignment create object reference(Python variables are more like pointers than data storage areas.

2) Names are created when first assigned. (No need to predeclare names ahead of time) 

3) Names must be assigned before being referenced 

4) Some operations perform assignments implicitly.( not just = statement, but also functions, class definitions, module imports and so on can work as assignment)


2. Assignment Statement Forms



3. 

1) Tuple- and list-unpacking assignments


2) Sequence assignments:(it supports any iterable object  on the right, not just sequence)

Ex: 1) a,*c,b=map(abs,[-1,-2,3,4,5])

       2)  Advanced sequence assignment patterns: ((a, b), c) = ('SP', 'AM') 

   (use string slicing,index, concatenate,nested sequence)             (a, b), c = string[:2], string[2:]


3) Extended sequence unpacking: 

A. starred name, *X (when a starred name is used, the number of items in he target on the left need not match the length of the subject sequence, starred name *X can appear anywhere in the targets 

B. while sequence unpacking always return a list for multiple matched items.(while slicing returns a sequence of the same type as the object  sliced.)

Using extended sequence unpacking: *a, b = 'spam' >>>a=['s','p','a']

Using Slicing: S = 'spam'  S[0], S[1:3], S[3]>>>('s', 'pa', 'm')

C. Boundary cases

a. the starred name may match just a single item, but is always assigned a list(Ex:a, b, c, *d =[1, 2, 3, 4]>>>d=[4]

b. if there is nothing left to match the starred name, it is assigned to an empty list.(Ex:a, b, c, e,*d =[1, 2, 3, 4]>>>d=[]

c. errors can still be triggered if there is more than one starred name.(Ex:a, *b, c, *d = 'seq')


D. 'first, rest' splitting coding pattern (a,*b)

        'rest,last' splitting coding pattern (*a, b)


4) Multiple-target assignments

    shared references


5) Augmented assignments



Note that 

1) += for a list is not exactly the same as a + and = in all cases-for lists+=allows arbitrary sequences (just like extend), but concatenation does not)

>>> L = []
>>> L += 'spam'

while L=L+'spam' will raise an error(TypeError: can only concatenate list (not "str") to list)

2) += is an in-place change for lists, so it's not like +concatenation, which always makes a new object. and this will matter if other names reference the object being changed. 






0 0