hopeless-dream

导航

Python的封装和解构

封装

使用逗号将多个值组合在一起,返回一个元组,省略了小括号

In [72]: tp1=(1,2)

In [73]: type(tp1)
Out[73]: tuple

In [74]: tp2=1,2

In [75]: type(tp2)
Out[75]: tuple

In [76]: tp2='ab',2,'c'

In [77]: tp2
Out[77]: ('ab', 2, 'c')
In [78]: tp2=[1,2],'ab',2,'c'

In [79]: tp2
Out[79]: ([1, 2], 'ab', 2, 'c')

解构

将线性结构解开,顺序赋值给其他变量(左边接受赋值的变量数要和右边数据结构解开的元素数一致)

In [80]: str1='abc','bcd'

In [81]: sub1,sub2=str1

In [82]: sub1
Out[82]: 'abc'

In [83]: sub2
Out[83]: 'bcd'

解构

In [91]: a,b={1,2}

In [92]: a
Out[92]: 1

In [93]: b
Out[93]: 2

In [94]: a,b={'a':10,'b':30}

In [95]: a
Out[95]: 'b'

In [96]: b
Out[96]: 'a'

In [98]: a,b={1,2,3}
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-98-14e2385ba548> in <module>
----> 1 a,b={1,2,3}

ValueError: too many values to unpack (expected 2)

In [106]: [a,b]=(1,2)

In [107]: a
Out[107]: 1

In [108]: b
Out[108]: 2

In [109]: [a,b]=10,20

In [110]: a
Out[110]: 10

In [111]: b
Out[111]: 20

In [112]: (a,b)={'a':10,'b':30}

In [113]: a
Out[113]: 'b'

In [114]: b
Out[114]: 'a'

结构的本质

下面的例子:(a,b)接受右边的值后组成的一个元组,但是没有变量被赋值(a,b)这个元组,ipython使用 _ 来接受被遗弃的变量

In [121]: (a,b)=2,3

In [122]: a,b
Out[122]: (2, 3)

In [123]: _
Out[123]: (2, 3)

组合使用封装和解构(bubble)

In [84]: a = 1

In [85]: b = 2

In [86]: tmp =a

In [87]: a = b

In [88]: b = tmp

In [89]: a
Out[89]: 2

In [90]: b
Out[90]: 1

与下面的表达式等价:

a, b = b, a

上面的语句中,等号左边使用了结构,右边使用封装

Python3中的解构

使用*VARIABLE 接收,*VARIABLE接收后组成一个列表

 

In [1]: lst= list(range(10))

In [2]: a,*mid,b = lst

In [3]: a
Out[3]: 0

In [4]: b
Out[4]: 9

 

In [8]: *head, tail=lst

In [9]: head
Out[9]: [0, 1, 2, 3, 4, 5, 6, 7, 8]

In [10]: head, *tail=lst

In [11]: tail
Out[11]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

不能给多个表达式

In [15]: a,*var1,b,*var2,tail=lst
  File "<ipython-input-15-7b7f4a61b498>", line 4
SyntaxError: two starred expressions in assignment

 

切片练习

从lst=[1,(3,4,5),10]中提取出5

In [22]: _,[*_,tail],_=lst

In [23]: tail
Out[23]: 5

 

posted on 2020-09-15 15:04  hopeless-dream  阅读(162)  评论(0编辑  收藏  举报