python学习—基础篇

一、变量赋值及命名规则
① 声明一个变量及赋值

复制代码

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 # _author_soloLi
4 name1="solo"
5 name2=name1
6 print(name1,name2)
7 name1 = "hehe"
8 print(name1,name2)

复制代码

#name1的值为hehe,name2的值为solo

② 变量命名的规则

1 1、变量名只能是 字母、数字或下划线的任意组合
2 2、变量名的第一个字符不能是数字
3 3、以下关键字不能声明为变量名['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global','if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

 

二、字符编码
python解释器在加载 .py 文件中的代码时,会对内容进行编码(默认ascill)

ASCII:最多只能用 8位来表示(一个字节),即:2**8 = 256,所以,ASCII码最多只能表示 256 个符号。显然ASCII码无法将世界上的各种文字和符号全部表示。

Unicode:它为每种语言中的每个字符设定了统一并且唯一的二进制编码,规定虽有的字符和符号最少由 16 位来表示(2个字节),即:2 **16 = 65536,注:此处说的的是最少2个字节,可能更多。

UTF-8:是对Unicode编码的压缩和优化,他不再使用最少使用2个字节,而是将所有的字符和符号进行分类:ascii码中的内容用1个字节保存、欧洲的字符用2个字节保存,东亚的字符用3个字节保存...
注:python2.x版本,默认支持的字符编码为ASCll python3.x版本,默认支持的是Unicode,不用声明字符编码可以直接显示中文。

 扩展:字符编码和转码,bytes和str区别

    Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式混用str和bytes(类似int和long之间自动转换),正是这使得两者的区分特别清晰。你不能拼接字符串和字节包,也无法在字节包里搜索字符串(反之亦然),也不能将字符串传入参数为字节包的函数(反之亦然)。这是件好事。不管怎样,字符串和字节包之间的界线是必然的,下面的图解非常重要,务请牢记于心:

字符串可以编码成字节包,而字节包可以解码成字符串:

复制代码

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 #-Author-solo
4 msg = "里约奥运"
5  
6 print(msg.encode("utf-8"))                      #如果不指定编码格式,默认为utf-8
7 #b'\xe9\x87\x8c\xe7\xba\xa6\xe5\xa5\xa5\xe8\xbf\x90'
8 print(b'\xe9\x87\x8c\xe7\xba\xa6\xe5\xa5\xa5\xe8\xbf\x90'.decode("utf-8"))
9 #里约奥运

复制代码

为什么要进行编码和转码?
  由于每个国家电脑的字符编码格式不统一(列中国:GBK),同一款软件放到不同国家的电脑上会出现乱码的情况,出现这种情况如何解决呢?! 当然由于所有国家的电脑都支持Unicode万国码,那么我们可以把Unicode为跳板,先把字符编码转换为Unicode,在把Unicode转换为另一个国家的字符编码(例韩国),则不会出现乱码的情况。当然这里只是转编码集并不是翻译成韩文不要弄混了。

① Python3.0进行编码转换(默认Unicode编码)

复制代码

1 name = "李伟"                     #此时name为Unicode编码
2 name1 = name.encode("utf-8")      #Unicode转为UTF-8
3 name2 = name1.decode("utf-8")     #UTF-8转为Unicode
4 
5 name3 = name.encode("gbk")       #Unicode转为GBK
6 name4 = name3.decode("gbk")      #GBK转为Unicode

复制代码

② Python2.0中的编码转换(默认ascii编码)

 View Code

 

三、用户交互及字符串拼接

复制代码

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # _author_soloLi
 4 # python2.X与python3.X区别:    python2.X raw_input = python3.X input
 5 # 提示用户输入姓名、年龄、工作、工资并以信息列表的形式打印出
 6 
 7  name = input("Please input your name:")
 8  age = int(input("Please input your age:"))  #str强制转换为int
 9  job = input("Please input your job:")
10  salary = input("Please input your salary:")
11 
12  info1 = '''
13  ------------  Info of %s  ---------
14  Name:%s
15  Age:%d
16  Job:%s
17  Salary:%s
18  ''' %(name,name,age,job,salary)     #%s检测数据类型为字符串,%d检测数据类型为整数,%f检测数据类型为浮点数 强制
19  print(info1)
20 
21 # info2 = '''
22 # ------------  Info of {_Name}  ---------
23 # Name:{_Name}
24 # Age:{_Age}
25 # Job:{_Job}
26 # Salary:{_Salary}
27 # ''' .format(_Name=name,
28 #             _Age=age,
29 #             _Job=job,
30 #             _Salary=salary)
31 # print(info2)
32 
33 # info3 = '''
34 # ------------  Info of {0}  ---------
35 # Name:{0}
36 # Age:{1}
37 # Job:{2}
38 # Salary:{3}
39 # ''' .format(name,age,job,salary)
40 # print(info3)

复制代码

对比分析:
1、% :无法同时传递一个变量和元组,又是要加()来保证不抛出typeerror异常
2、+ :每增加一个一个+就会开辟一块新的内存空间
3、.fomat :不会出现上述问题,有时使用为了兼容Python2版本。如使用logging库

 

四、循环语句(if、while、for、三元运算)

复制代码

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # _author_soloLi
 4 ################## if语句 ######################
 5 # A = 66
 6 #
 7 # B = int(input("请输入0-100的幸运数字:"))
 8 #
 9 # if B == A:                     #母级顶格写
10 #     print ("恭喜你猜对了!")    #子级强制缩进写
11 # elif B > A :
12 #     print ("猜小了")
13 # else:
14 #     print ("猜大了")
15 
16 
17 ################## while语句 ######################
18 # A = 66
19 # count = 0                    # 设置初始值count=0
20 #
21 # while count < 3 :
22 #
23 #     B = int(input("请输入0-100的数字:"))
24 #
25 #     if B == A:
26 #         print ("恭喜你猜对了!")
27 #         break
28 #     elif B > A :
29 #         print ("猜大了")
30 #     else:
31 #         print ("猜小了")
32 #     count += 1
33 # else:
34 #     print ("你猜的次数太多了!")
35 
36 
37 ################## for语句 ######################
38 A = 66
39 i=1
40 for i in range(3):# while判断count是否小于3,如果小于3则:
41     print("i=",i)
42     B = int(input("请输入0-100的数字:"))
43     if B == A:
44         print ("恭喜你猜对了!")
45         break
46     elif B > A :
47         print ("猜小了")
48     else:
49         print ("猜大了")
50     i+=1
51 else:
52     print ("你猜的次数太多了!")
53 
54 
55 ################## 三元运算 ######################
56  # esult = 值1 if 条件 else 值2
57  # 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量

复制代码

 

五、基本数据类型

复制代码

# ①数字
# 1.整型int
#     作用:年纪,等级,身份证号,qq号等整型数字相关
# 2.浮点型float
#     作用:薪资,身高,体重,体质参数等浮点数相关
# 3.长整形
#     python3中没有长整形的概念
# 进制的转换:bin(转成二进制)、oct(转成八进制)、hex(转成十六进制)
#
# ②字符串
# 作用:名字,性别,国籍,地址等描述信息
# 常用操作:1.移除空白:       strip    (参数1:移除什么符号)
#           2.切分:           split  (参数1:以什么符号进行切割,参数2:最大切割次数)  切割成列表
#           3.长度:           len     统计的字符的长度
#           4.切片:           []     (参数1:起始位置:参数2:步长)   顾头不顾尾
#           5.替换:           replace(参数1:old,参数2:new,参数3:替换第几个)
#           6.拼接:           format
#           7.索引:           只能取
#           8.判断开头或结尾: startswith,endswith
#           9.其他。。。
#
# ③列表
# 作用:多个装备,多个爱好,多门课程,多个女朋友等
# 常用操作:1.索引:           即可存也可以取
#           2.切片:           []  切成新的列表
#           3.追加:           append
#           4.删除:           remove(按照值)/pop(按照索引)
#           5.长度:           len    统计的列表的元素个数
#           6.成员运算(包含):in
#           7.循环:
#           8.插入:           insert
#           9.其他。。。
#
# ④元组
# 作用:存多个值,对比列表来说,元组不可变,主要是用来读
# 常用操作:除了不能改变元组的之外,其他操作跟列表相同
#           1.索引:           index只能取
#           2.切片:           []
#           3.长度:           len
#           4.循环:
#           5.成员运算(包含):in
#           6.统计:           count
#
# ⑤字典
# 作用:存多个值,key-value(键值对)存取,取值速度快
# 常用操作:1.按key存取值:可存可取
#           2.循环:            无序
#           3.长度:           len
#           4.删除:           pop  第2个参数设置none  程序即使取不到值也不报错
#           5.成员运算(包含):in
#           6.取值:           get(不存在程序不报错)/info(不存在程序报错)
#           7.其他。。。
#
# ⑥集合
# 作用:去重,关系运算,
# 常用操作:1.长度:           len
#           2.添加:           add(只能添加一个元素)/update(可以添加多个元素)
#           3.删除:           remove(删除指定元素)/pop(随机删除元素)/discard(删除指定元素,与remove区别在于,如果元素不存在也不会报错)
#           4.交集:           &
#           5.差集:           -
#           6.对称差集:       ^
#           7.成员运算:       in
#           8.合集:           |
#           9.父集:           >,>=
#          10.子集:           <,<=
#
# 小结:
# 按存值个数区分
#     标量/原子类型:数字,字符串
#     容器类型:列表,元组,字典
#
# 按可变不可变区分
#     可变:列表,字典
#     不可变:数字,字符串,元组
#
# 按访问方式区分
#     直接访问:数字
#     按照索引访问(序列类型):字符串,列表,元组
#     key访问(映射类型)    字典

复制代码

一、整型
如: 18、73、84
类型常用功能:

复制代码

 1 abs(x)      #返回绝对值
 2 x+y,x-y,x*y,x/y  #加减乘除
 3 x/y         #取商,浮点数相除保留余数
 4 x//y        #取商,浮点数相除余数为0
 5 x%y         #取余
 6 x**y         #幂次方
 7 cmp(x,y)    #两个数比较,返回True或False相等则为0
 8 coerce(x,y) #强制把两个数生成一个元组
 9 divmod(x,y) #相除得到商和余数组成的元组
10 float(x)    #转换为浮点型
11 str(x)      #转换为字符串
12 hex(x)      #转换为16进制
13 oct(x)      #转换8进制

复制代码

更多功能:

复制代码

  1 class int(object):
  2     """
  3     int(x=0) -> int or long
  4     int(x, base=10) -> int or long
  5     
  6     Convert a number or string to an integer, or return 0 if no arguments
  7     are given.  If x is floating point, the conversion truncates towards zero.
  8     If x is outside the integer range, the function returns a long instead.
  9     
 10     If x is not a number or if base is given, then x must be a string or
 11     Unicode object representing an integer literal in the given base.  The
 12     literal can be preceded by '+' or '-' and be surrounded by whitespace.
 13     The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 14     interpret the base from the string as an integer literal.
 15     >>> int('0b100', base=0)
 16     """
 17     def bit_length(self): 
 18         """ 返回表示该数字的时占用的最少位数 """
 19         """
 20         int.bit_length() -> int
 21         
 22         Number of bits necessary to represent self in binary.
 23         >>> bin(37)
 24         '0b100101'
 25         >>> (37).bit_length()
 26         """
 27         return 0
 28 
 29     def conjugate(self, *args, **kwargs): # real signature unknown
 30         """ 返回该复数的共轭复数 """
 31         """ Returns self, the complex conjugate of any int. """
 32         pass
 33 
 34     def __abs__(self):
 35         """ 返回绝对值 """
 36         """ x.__abs__() <==> abs(x) """
 37         pass
 38 
 39     def __add__(self, y):
 40         """ x.__add__(y) <==> x+y """
 41         pass
 42 
 43     def __and__(self, y):
 44         """ x.__and__(y) <==> x&y """
 45         pass
 46 
 47     def __cmp__(self, y): 
 48         """ 比较两个数大小 """
 49         """ x.__cmp__(y) <==> cmp(x,y) """
 50         pass
 51 
 52     def __coerce__(self, y):
 53         """ 强制生成一个元组 """ 
 54         """ x.__coerce__(y) <==> coerce(x, y) """
 55         pass
 56 
 57     def __divmod__(self, y): 
 58         """ 相除,得到商和余数组成的元组 """ 
 59         """ x.__divmod__(y) <==> divmod(x, y) """
 60         pass
 61 
 62     def __div__(self, y): 
 63         """ x.__div__(y) <==> x/y """
 64         pass
 65 
 66     def __float__(self): 
 67         """ 转换为浮点类型 """ 
 68         """ x.__float__() <==> float(x) """
 69         pass
 70 
 71     def __floordiv__(self, y): 
 72         """ x.__floordiv__(y) <==> x//y """
 73         pass
 74 
 75     def __format__(self, *args, **kwargs): # real signature unknown
 76         pass
 77 
 78     def __getattribute__(self, name): 
 79         """ x.__getattribute__('name') <==> x.name """
 80         pass
 81 
 82     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 83         """ 内部调用 __new__方法或创建对象时传入参数使用 """ 
 84         pass
 85 
 86     def __hash__(self): 
 87         """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
 88         """ x.__hash__() <==> hash(x) """
 89         pass
 90 
 91     def __hex__(self): 
 92         """ 返回当前数的 十六进制 表示 """ 
 93         """ x.__hex__() <==> hex(x) """
 94         pass
 95 
 96     def __index__(self): 
 97         """ 用于切片,数字无意义 """
 98         """ x[y:z] <==> x[y.__index__():z.__index__()] """
 99         pass
100 
101     def __init__(self, x, base=10): # known special case of int.__init__
102         """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
103         """
104         int(x=0) -> int or long
105         int(x, base=10) -> int or long
106         
107         Convert a number or string to an integer, or return 0 if no arguments
108         are given.  If x is floating point, the conversion truncates towards zero.
109         If x is outside the integer range, the function returns a long instead.
110         
111         If x is not a number or if base is given, then x must be a string or
112         Unicode object representing an integer literal in the given base.  The
113         literal can be preceded by '+' or '-' and be surrounded by whitespace.
114         The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
115         interpret the base from the string as an integer literal.
116         >>> int('0b100', base=0)
117         # (copied from class doc)
118         """
119         pass
120 
121     def __int__(self): 
122         """ 转换为整数 """ 
123         """ x.__int__() <==> int(x) """
124         pass
125 
126     def __invert__(self): 
127         """ x.__invert__() <==> ~x """
128         pass
129 
130     def __long__(self): 
131         """ 转换为长整数 """ 
132         """ x.__long__() <==> long(x) """
133         pass
134 
135     def __lshift__(self, y): 
136         """ x.__lshift__(y) <==> x<<y """
137         pass
138 
139     def __mod__(self, y): 
140         """ x.__mod__(y) <==> x%y """
141         pass
142 
143     def __mul__(self, y): 
144         """ x.__mul__(y) <==> x*y """
145         pass
146 
147     def __neg__(self): 
148         """ x.__neg__() <==> -x """
149         pass
150 
151     @staticmethod # known case of __new__
152     def __new__(S, *more): 
153         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
154         pass
155 
156     def __nonzero__(self): 
157         """ x.__nonzero__() <==> x != 0 """
158         pass
159 
160     def __oct__(self): 
161         """ 返回改值的 八进制 表示 """ 
162         """ x.__oct__() <==> oct(x) """
163         pass
164 
165     def __or__(self, y): 
166         """ x.__or__(y) <==> x|y """
167         pass
168 
169     def __pos__(self): 
170         """ x.__pos__() <==> +x """
171         pass
172 
173     def __pow__(self, y, z=None): 
174         """ 幂,次方 """ 
175         """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
176         pass
177 
178     def __radd__(self, y): 
179         """ x.__radd__(y) <==> y+x """
180         pass
181 
182     def __rand__(self, y): 
183         """ x.__rand__(y) <==> y&x """
184         pass
185 
186     def __rdivmod__(self, y): 
187         """ x.__rdivmod__(y) <==> divmod(y, x) """
188         pass
189 
190     def __rdiv__(self, y): 
191         """ x.__rdiv__(y) <==> y/x """
192         pass
193 
194     def __repr__(self): 
195         """转化为解释器可读取的形式 """
196         """ x.__repr__() <==> repr(x) """
197         pass
198 
199     def __str__(self): 
200         """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
201         """ x.__str__() <==> str(x) """
202         pass
203 
204     def __rfloordiv__(self, y): 
205         """ x.__rfloordiv__(y) <==> y//x """
206         pass
207 
208     def __rlshift__(self, y): 
209         """ x.__rlshift__(y) <==> y<<x """
210         pass
211 
212     def __rmod__(self, y): 
213         """ x.__rmod__(y) <==> y%x """
214         pass
215 
216     def __rmul__(self, y): 
217         """ x.__rmul__(y) <==> y*x """
218         pass
219 
220     def __ror__(self, y): 
221         """ x.__ror__(y) <==> y|x """
222         pass
223 
224     def __rpow__(self, x, z=None): 
225         """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
226         pass
227 
228     def __rrshift__(self, y): 
229         """ x.__rrshift__(y) <==> y>>x """
230         pass
231 
232     def __rshift__(self, y): 
233         """ x.__rshift__(y) <==> x>>y """
234         pass
235 
236     def __rsub__(self, y): 
237         """ x.__rsub__(y) <==> y-x """
238         pass
239 
240     def __rtruediv__(self, y): 
241         """ x.__rtruediv__(y) <==> y/x """
242         pass
243 
244     def __rxor__(self, y): 
245         """ x.__rxor__(y) <==> y^x """
246         pass
247 
248     def __sub__(self, y): 
249         """ x.__sub__(y) <==> x-y """
250         pass
251 
252     def __truediv__(self, y): 
253         """ x.__truediv__(y) <==> x/y """
254         pass
255 
256     def __trunc__(self, *args, **kwargs): 
257         """ 返回数值被截取为整形的值,在整形中无意义 """
258         pass
259 
260     def __xor__(self, y): 
261         """ x.__xor__(y) <==> x^y """
262         pass
263 
264     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
265     """ 分母 = 1 """
266     """the denominator of a rational number in lowest terms"""
267 
268     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
269     """ 虚数,无意义 """
270     """the imaginary part of a complex number"""
271 
272     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
273     """ 分子 = 数字大小 """
274     """the numerator of a rational number in lowest terms"""
275 
276     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
277     """ 实属,无意义 """
278     """the real part of a complex number"""
279 
280 int
281 
282 int

复制代码

二、长整型
如:2147483649、9223372036854775807
类型常用功能:

1 #长整型功能与整形基本类似

更多功能:

复制代码

  1 class long(object):
  2     """
  3     long(x=0) -> long
  4     long(x, base=10) -> long
  5     
  6     Convert a number or string to a long integer, or return 0L if no arguments
  7     are given.  If x is floating point, the conversion truncates towards zero.
  8     
  9     If x is not a number or if base is given, then x must be a string or
 10     Unicode object representing an integer literal in the given base.  The
 11     literal can be preceded by '+' or '-' and be surrounded by whitespace.
 12     The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 13     interpret the base from the string as an integer literal.
 14     >>> int('0b100', base=0)
 15     4L
 16     """
 17     def bit_length(self): # real signature unknown; restored from __doc__
 18         """
 19         long.bit_length() -> int or long
 20         
 21         Number of bits necessary to represent self in binary.
 22         >>> bin(37L)
 23         '0b100101'
 24         >>> (37L).bit_length()
 25         """
 26         return 0
 27 
 28     def conjugate(self, *args, **kwargs): # real signature unknown
 29         """ Returns self, the complex conjugate of any long. """
 30         pass
 31 
 32     def __abs__(self): # real signature unknown; restored from __doc__
 33         """ x.__abs__() <==> abs(x) """
 34         pass
 35 
 36     def __add__(self, y): # real signature unknown; restored from __doc__
 37         """ x.__add__(y) <==> x+y """
 38         pass
 39 
 40     def __and__(self, y): # real signature unknown; restored from __doc__
 41         """ x.__and__(y) <==> x&y """
 42         pass
 43 
 44     def __cmp__(self, y): # real signature unknown; restored from __doc__
 45         """ x.__cmp__(y) <==> cmp(x,y) """
 46         pass
 47 
 48     def __coerce__(self, y): # real signature unknown; restored from __doc__
 49         """ x.__coerce__(y) <==> coerce(x, y) """
 50         pass
 51 
 52     def __divmod__(self, y): # real signature unknown; restored from __doc__
 53         """ x.__divmod__(y) <==> divmod(x, y) """
 54         pass
 55 
 56     def __div__(self, y): # real signature unknown; restored from __doc__
 57         """ x.__div__(y) <==> x/y """
 58         pass
 59 
 60     def __float__(self): # real signature unknown; restored from __doc__
 61         """ x.__float__() <==> float(x) """
 62         pass
 63 
 64     def __floordiv__(self, y): # real signature unknown; restored from __doc__
 65         """ x.__floordiv__(y) <==> x//y """
 66         pass
 67 
 68     def __format__(self, *args, **kwargs): # real signature unknown
 69         pass
 70 
 71     def __getattribute__(self, name): # real signature unknown; restored from __doc__
 72         """ x.__getattribute__('name') <==> x.name """
 73         pass
 74 
 75     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 76         pass
 77 
 78     def __hash__(self): # real signature unknown; restored from __doc__
 79         """ x.__hash__() <==> hash(x) """
 80         pass
 81 
 82     def __hex__(self): # real signature unknown; restored from __doc__
 83         """ x.__hex__() <==> hex(x) """
 84         pass
 85 
 86     def __index__(self): # real signature unknown; restored from __doc__
 87         """ x[y:z] <==> x[y.__index__():z.__index__()] """
 88         pass
 89 
 90     def __init__(self, x=0): # real signature unknown; restored from __doc__
 91         pass
 92 
 93     def __int__(self): # real signature unknown; restored from __doc__
 94         """ x.__int__() <==> int(x) """
 95         pass
 96 
 97     def __invert__(self): # real signature unknown; restored from __doc__
 98         """ x.__invert__() <==> ~x """
 99         pass
100 
101     def __long__(self): # real signature unknown; restored from __doc__
102         """ x.__long__() <==> long(x) """
103         pass
104 
105     def __lshift__(self, y): # real signature unknown; restored from __doc__
106         """ x.__lshift__(y) <==> x<<y """
107         pass
108 
109     def __mod__(self, y): # real signature unknown; restored from __doc__
110         """ x.__mod__(y) <==> x%y """
111         pass
112 
113     def __mul__(self, y): # real signature unknown; restored from __doc__
114         """ x.__mul__(y) <==> x*y """
115         pass
116 
117     def __neg__(self): # real signature unknown; restored from __doc__
118         """ x.__neg__() <==> -x """
119         pass
120 
121     @staticmethod # known case of __new__
122     def __new__(S, *more): # real signature unknown; restored from __doc__
123         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
124         pass
125 
126     def __nonzero__(self): # real signature unknown; restored from __doc__
127         """ x.__nonzero__() <==> x != 0 """
128         pass
129 
130     def __oct__(self): # real signature unknown; restored from __doc__
131         """ x.__oct__() <==> oct(x) """
132         pass
133 
134     def __or__(self, y): # real signature unknown; restored from __doc__
135         """ x.__or__(y) <==> x|y """
136         pass
137 
138     def __pos__(self): # real signature unknown; restored from __doc__
139         """ x.__pos__() <==> +x """
140         pass
141 
142     def __pow__(self, y, z=None): # real signature unknown; restored from __doc__
143         """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
144         pass
145 
146     def __radd__(self, y): # real signature unknown; restored from __doc__
147         """ x.__radd__(y) <==> y+x """
148         pass
149 
150     def __rand__(self, y): # real signature unknown; restored from __doc__
151         """ x.__rand__(y) <==> y&x """
152         pass
153 
154     def __rdivmod__(self, y): # real signature unknown; restored from __doc__
155         """ x.__rdivmod__(y) <==> divmod(y, x) """
156         pass
157 
158     def __rdiv__(self, y): # real signature unknown; restored from __doc__
159         """ x.__rdiv__(y) <==> y/x """
160         pass
161 
162     def __repr__(self): # real signature unknown; restored from __doc__
163         """ x.__repr__() <==> repr(x) """
164         pass
165 
166     def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
167         """ x.__rfloordiv__(y) <==> y//x """
168         pass
169 
170     def __rlshift__(self, y): # real signature unknown; restored from __doc__
171         """ x.__rlshift__(y) <==> y<<x """
172         pass
173 
174     def __rmod__(self, y): # real signature unknown; restored from __doc__
175         """ x.__rmod__(y) <==> y%x """
176         pass
177 
178     def __rmul__(self, y): # real signature unknown; restored from __doc__
179         """ x.__rmul__(y) <==> y*x """
180         pass
181 
182     def __ror__(self, y): # real signature unknown; restored from __doc__
183         """ x.__ror__(y) <==> y|x """
184         pass
185 
186     def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__
187         """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
188         pass
189 
190     def __rrshift__(self, y): # real signature unknown; restored from __doc__
191         """ x.__rrshift__(y) <==> y>>x """
192         pass
193 
194     def __rshift__(self, y): # real signature unknown; restored from __doc__
195         """ x.__rshift__(y) <==> x>>y """
196         pass
197 
198     def __rsub__(self, y): # real signature unknown; restored from __doc__
199         """ x.__rsub__(y) <==> y-x """
200         pass
201 
202     def __rtruediv__(self, y): # real signature unknown; restored from __doc__
203         """ x.__rtruediv__(y) <==> y/x """
204         pass
205 
206     def __rxor__(self, y): # real signature unknown; restored from __doc__
207         """ x.__rxor__(y) <==> y^x """
208         pass
209 
210     def __sizeof__(self, *args, **kwargs): # real signature unknown
211         """ Returns size in memory, in bytes """
212         pass
213 
214     def __str__(self): # real signature unknown; restored from __doc__
215         """ x.__str__() <==> str(x) """
216         pass
217 
218     def __sub__(self, y): # real signature unknown; restored from __doc__
219         """ x.__sub__(y) <==> x-y """
220         pass
221 
222     def __truediv__(self, y): # real signature unknown; restored from __doc__
223         """ x.__truediv__(y) <==> x/y """
224         pass
225 
226     def __trunc__(self, *args, **kwargs): # real signature unknown
227         """ Truncating an Integral returns itself. """
228         pass
229 
230     def __xor__(self, y): # real signature unknown; restored from __doc__
231         """ x.__xor__(y) <==> x^y """
232         pass
233 
234     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
235     """the denominator of a rational number in lowest terms"""
236 
237     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
238     """the imaginary part of a complex number"""
239 
240     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
241     """the numerator of a rational number in lowest terms"""
242 
243     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
244     """the real part of a complex number"""
245 
246 long
247 
248 long

复制代码

注:跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果

三、浮点型
如:3.14、2.88

类型常用功能:

 View Code

更多功能:

 View Code

四、字符串
如:'wupeiqi'、'alex'、'solo'

类型常用功能:

复制代码

 1 name = "my name is solo"
 2 print(name.capitalize())            #首字母大写
 3 #My name is solo
 4 print(name.count("l"))              #统计字符串出现某个字符的个数
 5 #2
 6 print(name.center(30,"-"))          #打印30个字符,不够的-补齐
 7 #--------my name is solo--------
 8 print(name.ljust(30,"-"))           #打印30个字符,不够的-补齐,字符串在左边
 9 #my name is solo----------------
10 print(name.endswith("solo"))         #判断字符串是否以solo结尾
11 #True
12 print(name[name.find("na"):])       #find寻找na所在的索引下标 字符串也可以切片
13 #name is solo
14 print("5.3".isdigit())              #判断字符是否为整数
15 #False
16 print("a_1A".isidentifier())        #判断是不是一个合法的标识符(变量名)
17 #True
18 print("+".join(["1","2","3"]))     #把join后的内容加入到前面字符串中,以+为分割符
19 #1+2+3
20 print("\nsolo".strip())              #去换行符
21 #solo
22 print("1+2+3+4".split("+"))        #以+为分隔符生成新的列表,默认不写为空格
23 #['1', '2', '3', '4']
24 name = "my name is {name} and i an {year} old"
25 print(name.format(name="solo",year=20)
26 #my name is solo and i an 20 old
27 print(name.format_map({"name":"solo","year":20}))            #很少用
28 #my name is solo and i an 20 old
29 p = str.maketrans("abcdefli","12345678")         #转换  一一对应
30 print("lianzhilei".translate(p))
31 #781nzh8758

复制代码

更多功能:

 View Code

五、列表
如:[11,22,33,44,55]、['wupeiqi', 'alex','solo']
1、创建列表:

1 #两种创建方式
2 name_list = ['alex', 'seven', 'eric']
3 
4 name_list = list(['alex', 'seven', 'eric'])

2、列表类常用功能:
① 切片 

复制代码

 1 name_list = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
 2 print(name_list[0:3])       #取下标0至下标3之间的元素,包括0,不包括3
 3 #['Alex', 'Tenglan', 'Eric']
 4 print(name_list[:3])        #:前什么都不写,表示从0开始,效果跟上句一样
 5 #['Alex', 'Tenglan', 'Eric']
 6 print(name_list[3:])        #:后什么不写,表示取值到最后
 7 #['Rain', 'Tom', 'Amy']
 8 print(name_list[:])         #:前后都不写,表示取值所有
 9 #['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy']
10 print(name_list[-3:-1])     #从-3开始到-1,包括-3,不包括-1
11 #['Rain', 'Tom']
12 print(name_list[1:-1])      #从1开始到-1,下标有正有负时,正数在前负数在后
13 #['Tenglan', 'Eric', 'Rain', 'Tom']
14 print(name_list[::2])       #2表示,每个1个元素,就取一个
15 #['Alex', 'Eric', 'Tom']
16 #注:[-1:0] [0:0] [-1:2] 都是空

复制代码

② 追加

1 name_list = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
2 name_list.append("new")          #append追加,加到最后,只能添加一个
3 print(name_list)
4 #['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', 'new']

③ 插入

1 name_list = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
2 name_list.insert(3,"new")          #insert插入,把"new"加到下标3的位置
3 print(name_list)

④ 修改

1 name_list = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
2 name_list[2] = "solo"                #把下标2的字符串换成solo
3 print(name_list)

⑤ 删除

复制代码

 1 #3种删除方式
 2 name_list = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
 3 del name_list[3]                      #del删除,指定要删除的下标
 4 print(name_list)
 5 #['Alex', 'Tenglan', 'Eric', 'Tom', 'Amy']
 6 name_list.remove("Tenglan")          #remove删除,指定要删除的字符
 7 print(name_list)
 8 #['Alex', 'Eric', 'Tom', 'Amy']
 9 name_list.pop()                       #pop删除,删除列表最后一个值
10 print(name_list)
11 #['Alex', 'Eric', 'Tom']

复制代码

⑥ 扩展

 View Code

⑦ 拷贝

 View Code

⑧ 统计

 View Code

⑨ 排序和翻转

 View Code

⑩ 获取下标

 View Code

六、元组

如:(11,22,33,44,55)、('wupeiqi', 'alex','lzl')

1、创建元组:

 View Code

2、元组类常用功能:

 View Code

七、字典 无序
如:{'name': 'wupeiqi', 'age': 18} 、{'host': 'solo.solo.solo.solo', 'port': 80}
注:字典一种key:value 的数据类型,也称键值对。字典dict是无序的,key值必须是唯一的,不能有重复。循环时,默认循环的是key
 1、创建字典

复制代码

1 #两种创建方式:
2 info_dic = {'stu1101': "TengLan Wu",'stu1102': "LongZe Luola",'stu1103': "XiaoZe Maliya",}
3 print(info_dic)
4 #{'stu1102': 'LongZe Luola', 'stu1101': 'TengLan Wu', 'stu1103': 'XiaoZe Maliya'}
5 info_dic = dict({'stu1101': "TengLan Wu",'stu1102': "LongZe Luola",'stu1103': "XiaoZe Maliya",})
6 print(info_dic)
7 #{'stu1102': 'LongZe Luola', 'stu1101': 'TengLan Wu', 'stu1103': 'XiaoZe Maliya'}

复制代码

2、字典类常用功能:

① 增加

 View Code

② 修改

 View Code

③ 删除

 View Code

④ 查找value值

 View Code

⑤ 字典多级嵌套

 View Code

⑥ 循环

 View Code

八、集合 
如:{'solo', 33, 'alex', 22, 'eric', 'wupeiqi', 11}
注:集合是一个无序的,不重复的数据组合。去重性,把一个列表变成集合,就自动去重了。关系测试,测试两组数据之前的交集、差集、并集
1、创建集合

1 #标准创建方式
2 info_set = set(["alex","wupeiqi","eric","solo",11,22,33])
3 print(info_set,type(info_set))
4 #{33, 11, 'wupeiqi', 'solo', 'alex', 'eric', 22} <class 'set'>

2、集合类常用功能
① 添加

复制代码

1 #添加的两种方式
2 set_1 = set(["alex","wupeiqi","eric","solo"])
3 set_1.add(11)                         #add只能添加一个元素
4 print(set_1)
5 #{'alex', 'solo', 'eric', 11, 'wupeiqi'}
6 set_1 = set(["alex","wupeiqi","eric","solo"])
7 set_1.update([11,22,33])
8 print(set_1)                           #update可以添加多个元素
9 #{33, 11, 'alex', 'wupeiqi', 'eric', 22, 'solo'}

复制代码

② 删除

 View Code

3、集合关系测试
① 交集

 View Code

② 并集

 View Code

③ 差集

 View Code

④ 子集、父集

 View Code

⑤ 对称差集

 View Code

⑥ 运算符做关系测试

 View Code

 

六、模块初识

Python有大量的模块,从而使得开发Python程序非常简洁。类库有包括三中:
① 、Python内部提供的模块
②、业内开源的模块
③、程序员自己开发的模块:Python脚本的名字不要与模块名相同

1、sys模块(系统内置)
① sys.argv 用来捕获执行python脚本时传入的参数
② sys.stdin 标准信息输入
③ sys.stdout 标准定向输出
④ sys.stdout.flush 强制刷新标准输出缓存

复制代码

1 import time
2 import sys
3 for i in range(5):
4     print(i),
5     sys.stdout.flush()
6     time.sleep(1)
7 # 这样设计是为了打印一个数每秒五秒钟,但如果您运行它,因为它是现在(取决于您的默认系统缓冲),
8 # 你可能看不到任何输出 CodeGo.net,直到再一次全部,你会看到0 1 2 3 4打印到屏幕上。
9 # 这是输出被缓冲,除非你sys.stdout之后每print你不会看到从输出中取出sys.stdout.flush()网上看到的差别

复制代码

2、os模块(与系统进行交互)
① os.dir、os.popen调用当前系统命令

3、platform模块(识别当前运行的系统)

 

七、运算符
1、算数运算:


2、比较运算:


3、赋值运算:


4、逻辑运算:


5、成员运算:


6、身份运算:


7、位运算:


8、运算符优先级:

 

八、深浅拷贝剖析
1、对象赋值(创建列表变量Alex,变量包含子列表,通过变量Alex给变量solo赋值,然后对变量Alex的元素进行修改,此时solo会有什么变化呢?)

 View Code

初始条件: Alex = ["Alex", 28, ["Python", "C#", "JavaScript"]]
对象赋值: solo = Alex           #直接赋值
对象赋值结果:solo = ["Alex", 28, ["Python", "C#", "JavaScript"]]
对象赋值时是进行对象引用(内存地址)的传递,被赋值的变量并没有开辟新内存,两个变量共用一个内存地址

修改对象赋值:solo = ['Mr.Wu', 28, ['Python', 'C#', 'JavaScript', 'CSS']]
str是不可变类型,所以当修改元素Alex为Mr.Wu时,内存地址发生改变;list是可变类型,元素['Python', 'C#', 'JavaScript', 'CSS']修改完后,内存地址没有改变

2、浅拷贝(创建列表变量Alex,变量包含子列表,通过copy模块的浅拷贝函数copy()对变量Alex进行拷贝,当对Alex进行操作时,此时solo会如何变化?)

 View Code

初始条件: Alex = ["Alex", 28, ["Python", "C#", "JavaScript"]]
浅拷贝: solo = copy.copy(Alex)         #通过copy模块里面的浅拷贝函数copy()
浅拷贝结果: solo = ["Alex", 28, ["Python", "C#", "JavaScript"]]
浅拷贝时变量solo新建了一块内存(10201848),此内存记录了list中元素的地址;对于list中的元素,浅拷贝会使用原始元素的引用(内存地址)

修改浅拷贝: solo = ['Mr.Wu', 28, ['Python', 'C#', 'JavaScript', 'CSS']]
str是不可变类型,所以当修改元素Alex为Mr.Wu时,内存地址发生改变;list是可变类型,元素['Python', 'C#', 'JavaScript', 'CSS']修改完后,内存地址没有改变

3、深拷贝(创建列表变量Alex,变量包含子列表,通过copy模块的深拷贝函数deepcopy()对变量Alex进行拷贝,当对Alex进行操作时,此时solo会如何变化?)

 View Code

初始条件: Alex = ["Alex", 28, ["Python", "C#", "JavaScript"]]
深拷贝: solo = copy.deepcopy(Alex) #通过copy模块里面的深拷贝函数deepcopy()
深拷贝结果: solo = ["Alex", 28, ["Python", "C#", "JavaScript"]]
深拷贝时变量solo新建了一块内存(10201848),此内存记录了list中元素的地址;但是,对于list中第三个元素(['Python', 'C#', 'JavaScript'])重新生成了一个地址(6203512),此时两个变量的第三个元素的内存引用地址不同

修改深拷贝: solo = ['Mr.Wu', 28, ['Python', 'C#', 'JavaScript', 'CSS']]
str是不可变类型,所以当修改元素Alex为Mr.Wu时,内存地址发生改变;list是可变类型,元素['Python', 'C#', 'JavaScript', 'CSS']修改完后,内存地址没有改变,但是Alex和solo在第三个元素引用的本就不同

4、对于拷贝有一些特殊情况
(1)对于非容器类型(如数字、字符串、和其他'原子'类型的对象)没有拷贝这一说
(2)也就是说,对于这些类型,"obj is copy.copy(obj)" 、"obj is copy.deepcopy(obj)"
(3)如果元祖变量只包含原子类型对象,则不能深拷贝
①为什么要拷贝?
答:当进行修改时,想要保留原来的数据和修改后的数据
②数字字符串 和 集合 在修改时的差异? (深浅拷贝不同的终极原因)
答:在修改数据时:
               数字字符串:在内存中新建一份数据
               集合:修改内存中的同一份数据
③对于集合,如何保留其修改前和修改后的数据?
答:在内存中拷贝一份
④对于集合,如何拷贝其n层元素同时拷贝?
答:深拷贝

 

九、文件操作

(1)打开文件: 文件句柄 = file('文件路径', '模式')
python中打开文件有两种方式,即:open(...) 和 file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open。
1、打开文件的模式:
  r, 只读模式【默认】
  w,只写模式【不可读;不存在则创建;存在则删除内容;】
  a, 追加模式【不可读;不存在则创建;存在则只追加内容;】
2、"+" 同时读写某个文件:
  r+,可读写文件。【可读;可写;可追加】
  w+,写读
  a+,追加读

复制代码

1 总结1:r+模式下,如果在.write()进行写入内容前,有print()输出,则要写的内容会从文件尾部开始写入,使用的是读、追加模式;如果在.write()进行写入内容前,是seek()移动光标,则要写的内容会从移动到的光标开始进行写入,会把原来的内容覆盖掉,而不是整体后移,这点要记住;如果在.write()进行写入内容前,既没有print()也没有seek()光标移动,这种情况之前想的的情况,就是r+读写模式能先写后读吗?r+模式下默认光标在文件的首部,此时会直接从文件开头进行写入,效果等同于seek(0)。关于最后一点,参考a+模式。
2 总结2:读写模式一定要先写后读吗?能不能先读后写?  如果先读的话,由于用的是w+模式打开的文件,打开后会清空原文件内容,所有读取的到东西是空的。另W+模式后期用的很少,了解即可,包括a+追加读这种模式;另w+模式下,光标会跟随文件写入移到到文件末尾,不用seek移到光标的话,打印内容为空
3 注:w+模式下,关于.write()跟seek()和print()的关系与r+模式下是一样一样的。w+打开文件后先清空,然后追加写,如果.write()前有seek()的话会从光标位置覆盖写。
4 总结3:通过上面的程序可以得出,a+模式下光标位置为文件末尾,如果要print()的话要结合seek()进行使用;另外与r+、w+不同的是,.write()与seek()没有关系,只能写内容到文件末尾,一直都是追加模式!

复制代码

 

3、"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
  rU
  r+U
4、"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
  rb 二进制读
  wb 二进制写(ab也一样)
  ab
(2)文件操作常用功能:
1、read()、readline()、readlines()的区别
  print(info_file.read()) #read参数,读取文件所有内容
  print(info_file.readline()) #readline,只读取文章中的一行内容
  print(info_file.readlines()) #readlines,把文章内容以换行符分割,并生成list格式,数据量大的话不建议使用
2、seek、tell光标
  data = info_file.read() #默认光标在起始位置,.read()读取完后,光标停留到文件末尾
  print(info_file.tell()) #tell 获取当前的光标位
  info_file.seek(0) #seek 移动光标到文件首部
3、文件循环
  for index,line in enumerate(info_file.readlines()): #先把文件内容以行为分割生成列表,数据量大不能用
  for line in info_file: #建议使用方法,每读取一行,内存会把之前的空间清空,不会占用太多内存
4、flush 刷新
  sys.stdout.flush() #flush 强制刷新缓存到内存的数据写入硬盘
5、truncate 截断
  truncate跟光标位置无关,从文件首部开始截取字符;如果是truncate(0)会把文件清空
6、with 语句
  为了避免打开文件后忘记关闭,可以通过管理上下文,即:
    with open('log','r') as f:
    ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
    with open('log1') as obj1, open('log2') as obj2:
    pass 
(3)文件修改方式:
1、把文件读取到内存当中,对内存进行修改,把修改后的内容写入到原文件(旧内容被清空)
2、如果在硬盘上直接写,会进行覆盖,硬盘上不能进行插入,原来的内容不会整体后移,而是直接覆盖掉
3、把文件读取到内存当中,对内存进行修改,把修改的内容另存为新的文件(旧文件保留)
  ① 另存方式
  ② r+模式
  ③ a+模式

 

十、函数

①格式

复制代码

1     def 函数名(参数):
2             ....
3             函数体
4             ....
5             return 返回值
6     函数名()

复制代码

②形参:  def func(name): // name 叫做函数func的形式参数,简称:形参
③实参:  func("solo") // 'solo' 叫做函数func的实际参数,简称:实参
④默认参数: def stu_register(name,age,course,country="CN") // 位置参数
⑤关键参数: stu_register(age=22,name='lzl',course="python")  // 关键参数必须放在位置参数之后

复制代码

形参:在定义函数时,括号内的参数成为形参
特点:形参就是变量名
# def foo(x,y): #x=1,y=2
#     print(x)
#     print(y)

实参:在调用函数时,括号内的参数成为实参
特点:实参就是变量值
# foo(1,2)

在调用阶段实参(变量值)才会绑定形参(变量名)
调用结束后,解除绑定

参数的分类
位置参数:按照从左到右的顺序依次定义的参数
    位置形参:必须被传值,并且多一个不行,少一个也不行
    位置实参:与形参按照位置一一对应

# def foo(x,y):
#     print(x)
#     print(y)
#
# foo('egon',1,2)


关键字实参:指的是按照name=value的形式,指名道姓地给name传值
# def foo(name,age):
#     print(name)
#     print(age)



# foo('egon',18)
# foo(age=18,name='egon')

关键字实参需要注意的问题是:
# def foo(name,age,sex):
#     print(name)
#     print(age)
#     print(sex)

# foo('egon',18,'male')
# print('======>')
# foo(sex='male',age=18,name='egon')
# foo('egon',sex='male',age=18)

问题一:语法规定位置实参必须在关键字实参的前面
# foo('egon',sex='male',age=18)

问题二:一定不要对同一个形参传多次值
# foo('egon',sex='male',age=18,name='egon1')

# foo('male',age=18,name='egon1')



默认参数(默认形参):在定义阶段,就已经为形参赋值,意味在调用阶段可以不用传值
# def foo(x,y=1111111):
#     print(x)
#     print(y)
#
#
# foo(1,'a')
#
# def register(name,age,sex='male'):
#     print(name,age,sex)
#
#
# register('asb',73)
# register('wsb',38)
# register('ysb',84)
# register('yaya',28,'female')


默认参数需要注意的问题
问题一:默认参数必须放在位置参数之后
# def foo(y=1,x):
#     print(x,y)

问题二:默认参数只在定义阶段赋值一次,而且仅一次
# x=100
# def foo(a,b=x):
#     print(a,b)
#
# x=111111111111111111111111111111
# foo('egon'

问题三:默认参数的值应该定义成不可变类型



#可变长参数指的是实参的个数多了
#实参无非位置实参和关键字实参两种

#形参必须要两种机制来分别处理按照位置定义的实参溢出的情况:*
#跟按照关键字定义的实参溢出的情况:**

# def foo(x,y,*args): #nums=(3,4,5,6,7)
#     print(x)
#     print(y)
#     print(args)

# foo(1,2,3,4,5,6,7) #*
# foo(1,2) #*



#*args的扩展用法
# def foo(x,y,*args): #*args=*(3,4,5,6,7)
#     print(x)
#     print(y)
#     print(args)
#
# # foo(1,2,3,4,5,6,7) #*
#
#
# foo(1,2,*(3,4,5,6,7)) #foo(1,2,3,4,5,6,7)


# def foo(x,y=1,*args): #
#     print(x)
#     print(y)
#     print(args)
#
# # foo('a','b',*(1,2,3,4,5,6,7)) #foo('a','b',1,2,3,4,5,6,7)
# # foo('egon',10,2,3,4,5,6,9,y=2) #报错
# foo('egon',10,2,3,4,5,6,9)









# def foo(x,y,**kwargs): #nums={'z':3,'b':2,'a':1}
#     print(x)
#     print(y)
#     print(kwargs)
# foo(1,2,z=3,a=1,b=2) #**


# def foo(x,y,**kwargs): #kwargs={'z':3,'b':2,'a':1}
#     print(x)
#     print(y)
#     print(kwargs)
#
# foo(1,2,**{'z':3,'b':2,'a':1}) #foo(1,2,a=1,z=3,b=2)


# def foo(x, y):  #
#     print(x)
#     print(y)
#
# foo(**{'y':1,'x':2})  # foo(y=1,x=2)







# def foo(x,*args,**kwargs):#args=(2,3,4,5) kwargs={'b':1,'a':2}
#     print(x)
#     print(args)
#     print(kwargs)
#
#
# foo(1,2,3,4,5,b=1,a=2)


#这俩东西*args,**kwargs干甚用???
def register(name,age,sex='male'):
    print(name)
    print(age)
    print(sex)


# def wrapper(*args,**kwargs): #args=(1,2,3) kwargs={'a':1,'b':2}
#     # print(args)
#     # print(kwargs)
#     register(*args,**kwargs)
#     # register(*(1, 2, 3),**{'a': 1, 'b': 2})
#     # register(1, 2, 3,a=1,b=2)
#
#
# wrapper(1,2,3,a=1,b=2)

import time

# def register(name,age,sex='male'):
#     # start_time=time.time()
#     print(name)
#     print(age)
#     print(sex)
#     time.sleep(3)
    # stop_time=time.time()
    # print('run time is %s' %(stop_time-start_time))

# def wrapper(*args, **kwargs): #args=('egon',) kwargs={'age':18}
#     start_time=time.time()
#     register(*args, **kwargs)
#     stop_time=time.time()
#     print('run time is %s' %(stop_time-start_time))
#
#
# wrapper('egon',age=18)

# register('egon',18)










#命名关键字参数:  在*后面定义的形参称为命名关键字参数,必须是被以关键字实参的形式传值
# def foo(name,age,*args,sex='male',group):
#     print(name)
#     print(age)
#     print(args)
#     print(sex)
#     print(group)
#
# foo('alex',18,19,20,300,group='group1')





def foo(name,age=18,*args,sex='male',group,**kwargs):
    pass

复制代码

⑥动态参数/非固定参数(*args 和 **kwargs):

1 (1)*args:*args会把多传入的实参变成一个元组的类型;即使传入的是list类型也会变成元组,成为元组中的一个元素;另函数中有*args与其他形参的时候,*args一定要写到其 他形参的后面,否则传入的实参都会被传入到*args当中打印成元组;还有如果没有多出传入的实参即*args没有值的时候,*args为空,不会报错。
2 (2)**kwargs:**kwargs会把多出的a=b这种类型的实参打印成字典的类型(要区分开与关键参数的区别,关键参数的实参有对应的形参),被当成多余的实参传入到了*args里面,所以**kwargs的值才为空,分别用*inf_list和**info_dict的方式传入到*args、**kwargs当中(stu_register("lzl",*info_list,**info_dict) //传入列表和字典)
3 总结:*args必须放到**kwargs前面(规定);位置参数一定要放到关键参数之前(规定);默认参数不能跟*args、**kwargs一块存在(会报错)。

⑦return 返回值: 如果不执行return,函数的默认返回值为None;当函数执行到return时,函数结束执行
⑧局部变量: name = "Alex Li" #定义变量name

1 def change_name(name):
2               name = "金角大王,一个有Tesla的男人"   #函数内部更改变量
3              函数内部对变量进行更改后,生效范围仅限于函数内部,对外部变量没有影响,这种变量称为局部变量;函数内部也可以让变量全局生效,需要加参数global,这种情况很少用。

⑨递归函数: 如果一个函数在内部调用自身本身,这个函数就是递归函数
           条件: 有结束条件、更深一层递归规模比上次递归有所减少、效率不高,递归层次过多会导致栈溢出

复制代码

1 写一个递归:
2              def func(n1,n2):        #获取斐波那契数列100之前的数字
3                  if n1 > 100:
4                      return
5                  print(n1)
6                  n3 = n1 + n2
7                  func(n2,n3)
8              func(0,1)

复制代码

匿名函数:不需要显式的指定函数

1 #普通函数               #换成匿名函数
2 def calc(n):            calc = lambda n:n**n
3     return n**n         print(calc(10)
4 print(calc(10))

⑪高阶函数: 变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

1 def add(x,y,f):
2     return f(x) + f(y)
3 res = add(3,-6,abs)
4 print(res)

⑫内置函数

⑬函数的调用顺序:被调用函数要在执行之前被定义

复制代码

 1 #函数错误的调用方式
 2 def func():                     #定义函数func()
 3     print("in the func")
 4     foo()                       #调用函数foo()
 5 func()                          #执行函数func()
 6 def foo():                      #定义函数foo()
 7     print("in the foo")
 8 
 9 #函数正确的调用方式
10 def func():                     #定义函数func()
11     print("in the func")
12     foo()                       #调用函数foo()
13 def foo():                      #定义函数foo()
14     print("in the foo")
15 func()                          #执行函数func()

复制代码

⑭高阶函数:1、某一函数当做参数传入另一个函数中。2、函数的返回值包含一个或多个函数

⑮内嵌函数:在一个函数体内创建另外一个函数(内嵌函数中定义的函数在全局中是无法直接执行的)

⑯装饰器:本质是函数(装饰其他函数),为其他函数添加附加功能的。
               遵循原则: 1.不能修改被装饰函数的源代码 2.不能修改被装饰函数的调用方式
               组成:装饰器由高阶函数+内嵌函数组成

 ⑰生成器:调用时才会生成相应数据的机制,称为生成器:generator

应用:可通过yield实现在单线程的情况下实现并发运算的效果(协程)

 协程

 ⑱迭代器

可迭代对象:可以直接作用于for循环的对象:Iterable 
可以直接作用于for循环的数据类型有:1、集合数据类型,如list、tuple、dict、set、str等;2、生成器,包括generator和带yield的generator function;
可以用isinstance()去判断一个对象是否是Iterable对象

1

2

3

from collections import Iterable

print(isinstance([], Iterable))

# True

迭代器:可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
用isinstance()判断一个对象是否是Iterator对象

1

2

3

from collections import Iterator

print(isinstance([], Iterator))

# True

小结:
1、凡是可作用于for循环的对象都是Iterable类型;
2、凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
3、集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象;
4、Python的for循环本质上就是通过不断调用next()函数实现的

 for循环

 等价效果(迭代器)

 

十一、常用模块

(一)、导入模块:导入模块的本质就是把python文件解释一遍;导入包的本质就是把包文件下面的init.py文件运行一遍

(二)、常用模块:

(1)time和datatime模块
  时间相关的操作,时间有三种表示方式:1、时间戳 1970年1月1日之后的秒,即:time.time()
                                                                      2、格式化的字符串 2014-11-11 11:11, 即:time.strftime('%Y-%m-%d')
                                                                      3、结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime()

复制代码

 1 import time
 2 print(time.time())              #时间戳
 3 #1472037866.0750718
 4 print(time.localtime())        #结构化时间
 5 #time.struct_time(tm_year=2016, tm_mon=8, tm_mday=25, tm_hour=8, tm_min=44, tm_sec=46, tm_wday=3, tm_yday=238, tm_isdst=0)
 6 print(time.strftime('%Y-%m-%d'))    #格式化的字符串
 7 #2016-08-25
 8 print(time.strftime('%Y-%m-%d',time.localtime()))
 9 #2016-08-25
10 print(time.gmtime())            #结构化时间
11 #time.struct_time(tm_year=2016, tm_mon=8, tm_mday=25, tm_hour=3, tm_min=8, tm_sec=48, tm_wday=3, tm_yday=238, tm_isdst=0)
12 print(time.strptime('2014-11-11', '%Y-%m-%d'))  #结构化时间
13 #time.struct_time(tm_year=2014, tm_mon=11, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=315, tm_isdst=-1)
14 print(time.asctime())
15 #Thu Aug 25 11:15:10 2016
16 print(time.asctime(time.localtime()))
17 #Thu Aug 25 11:15:10 2016
18 print(time.ctime(time.time()))
19 #Thu Aug 25 11:15:10 2016

复制代码

 datetime模块

 时间比较

(2)random模块:生成随机数(验证码)

 生成随机数

 验证码

(3)os模块:用于提供系统级别的操作(比如目录、路径等的操作)

 os模块

(4)sys模块:用于提供对解释器相关的操作(比如退出程序、版本信息等)

 sys模块

(5)shutil模块:高级的(文件、文件夹、压缩包)处理模块 (比如文件的拷贝、压缩等)

① shutil.copyfileobj 将文件内容拷贝到另一个文件中,可以部分内容

 shutil.copyfileobj

 把文件f1里的内容拷贝到f2当中

② shutil.copyfile 文件拷贝

 shutil.copyfile

 把文件f1里的内容拷贝到f2当中

③ shutil.copymode(src, dst) 仅拷贝权限。内容、组、用户均不变

 shutil.copymode

④ shutil.copystat(src, dst) 拷贝状态的信息,包括:mode bits, atime, mtime, flags

 shutil.copystat

⑤ shutil.copy(src, dst) 拷贝文件和权限

 shutil.copy

⑥ shutil.copy2(src, dst) 拷贝文件和状态信息

 shutil.copy2

⑦ shutil.copytree(src, dst, symlinks=False, ignore=None) 递归的去拷贝文件 拷贝多层目录

 shutil.copytree

⑧ shutil.rmtree(path[, ignore_errors[, onerror]]) 递归的去删除文件

 shutil.rmtree

⑨ shutil.move(src, dst) 递归的去移动文件

 shutil.move

⑩ shutil.make_archive(base_name, format,...) 创建压缩包并返回文件路径,例如:zip、tar
base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
        如:www                        =>保存至当前路径
        如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户,默认当前用户
group: 组,默认当前组
logger: 用于记录日志,通常是logging.Logger对象

 源码

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

 zipfile 压缩解压

 tarfile 压缩解压

 ZipFile 源码

 TarFile 源码

(6)json 和 pickle模块:文件只能存二进制或字符串,不能存其他类型,所以用到了用于序列化的两个模块

 

(7)shelve模块:shelve模块内部对pickle进行了封装,shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式 (可以存储数据、获取数据、给数据重新赋值)

 View Code

(8)xml模块:xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单(通过<>节点来区别数据结构)

 文件

 操作

(9)configparser模块:用于生成和修改配置文档(很少在程序中修改配置文件)

(10)hashlib模块:用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

 hashlib

 hmac 模块

(11)re模块:用于对python的正则表达式的操作;匹配(动态模糊的匹配);关键是匹配条件

 正则表达式

①、match:从起始位置开始去匹配

 View Code

②、search:最前面去匹配(不一定是最开始位置),匹配最前

 View Code

③、group与groups的区别

 View Code

④、findall上述两中方式均用于匹配单值,即:只能匹配字符串中的一个,如果想要匹配到字符串中所有符合条件的元素,则需要使用 findall;findall没有group 用法

 View Code

⑤、sub:用于替换匹配的字符串

 View Code

⑥、split:根据指定匹配进行分组(分割)

 View Code

(12)urllib模块:提供了一系列用于操作URL的功能(利用程序去执行各种HTTP请求。如果要模拟浏览器完成特定功能,需要把请求伪装成浏览器。伪装的方法是先监控浏览器发出的请求,再根据浏览器的请求头来伪装,User-Agent头就是用来标识浏览器的。)

 View Code

 

十二、面向对象

面向过程编程:通过代码的层层堆积来实现功能。不易迭代和维护。
函数式编程:将某功能代码封装到函数中,仅调用函数即可
面向对象编程:利用“类”和“对象”来创建各种模型来实现对真实世界的描述;使用面向对象编程的原因一方面是因为它可以使程序的维护和扩展变得更简单,并且可以大大提高程序开发效率 ,另外,基于面向对象的程序可以使它人更加容易理解你的代码逻辑,从而使团队开发变得更从容。

 经典类、新式类

 航班查询

类的特殊成员方法:
① __doc__  表示类的描述信息

 View Code

② __module__ 和 __class__
__module__ 表示当前操作的对象在哪个模块 
__class__ 表示当前操作的对象的类是什么

 View Code

③ __init__ 构造方法,通过类创建对象时,自动触发执行

④ __del__析构方法,当对象在内存中被释放时,自动触发执行

⑤ __call__ 对象后面加括号,触发执行
注:__init__的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

 View Code

⑥ __dict__ 查看类或对象中的所有成员

 View Code

⑦ __str__ 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值

 View Code

⑧ __getitem__、__setitem__、__delitem__
用于索引操作,如字典。以上分别表示获取、设置、删除数据

 View Code

⑨ __new__ \ __metaclass__

1 print type(f) # 输出:<class '__main__.Foo'>       表示,obj 对象由Foo类创建
2 print type(Foo) # 输出:<type 'type'>              表示,Foo类对象由 type 类创建

f对象是Foo类的一个实例,Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建

是由 type 类实例化产生那么问题来了,类默认是由 type 类实例化产生,type类中如何实现的创建类?类又是如何创建对象?
答:类中有一个属性 __metaclass__,其用来表示该类由 谁 来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看 类 创建的过程

 View Code

反射:通过字符串映射或修改程序运行时的状态、属性、方法。 有以下4个方法
① hasattr(obj,str) 判断一个对象obj里是否有对应的str字符串的方法
② getattr(obj,str) 根据字符串去获取obj对象里的对应的方法的内存地址

 View Code

③ setattr(obj,'y','z') obj.y = z 通过字符串添加属性

 View Code

④ delattr(obj,str) 删除obj.str 通过字符串删除属性

 View Code

十三、Python垃圾回收机制 

概述:和许多其它的高级语言一样,Python使用了垃圾回收器来自动销毁那些不再使用的对象。每个对象都有一个引用计数,当这个引用计数为0时Python能够安全地销毁这个对象

问题点:由于一次仅能有一个对象被回收,引用计数无法回收循环引用的对象。

解决方案:弱引用:减少循环引用,减少内存中不必要的对象存在的数量。对象可能在任何时刻被回收。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值