python小甲鱼笔记之一

成员操作符 in ; 逻辑操作符 and or ; 比较操作符 > < ; 重复操作符 * ;

迭代是能返回结果并作为初始化值的过程, 基本等同于for循环。

列表

通过=与通过切片赋值不同,前者只是增加了指向。

1
2
3
4
5
6
7
>>> l1 = [1,2,3]
>>> l2 = l1
>>> l1.sort(reverse=True)
>>> l1
[3, 2, 1]
>>> l2
[3, 2, 1]

元祖

赋值需注意,逗号是关键

1
2
3
4
5
6
7
8
9
10
>>> t = (1)
>>> type(t)
<class 'int'>
>>> s = 1,2,3
>>> type(s)
<class 'tuple'>
元祖只有一个元素是,正确写法如下
>>> t = (1,)
>>> type(t)
<class 'tuple'>

字符

字符不可改变

join连接符

1
2
>>> 'str'.join('12345')
'1str2str3str4str5'

函数

行参(parameter)与实参(argument)

收集参数 *params,如果有关键参数的话,要把他放前面

不能在函数内部修改全局变量,只能访问。

内嵌函数

内嵌函数只能在内部使用

闭包是函数式编程的一种方式。

1
2
3
4
5
6
7
8
9
>>> def fun(x):
def funb(y):
return x*y
return funb
>>> fun(8)
<function fun.<locals>.funb at 0x0229C738>
>>> fun(8)(5)
40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> def fun():
x = 5
def funb():
x *= x ##局部变量不可修改外部变量
return x
return funb()
>>> fun()
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
fun()
File "<pyshell#56>", line 6, in fun
return funb()
File "<pyshell#56>", line 4, in funb
x *= x
UnboundLocalError: local variable 'x' referenced before assignment
1
2
3
4
5
6
7
8
9
>>> def fun():
x = [5]
def funb():
x[0] *= x[0]
return x[0]
return funb()
>>> fun()
25
1
2
3
4
5
6
7
>>> def fun():
x = 5
def funb():
nonlocal x ##nonlocal
x *= x
return x
return funb()

字典

字典是python中唯一的映射关系

字典赋值方式 dict(([1,'one'],[2,'two'])),或者key,values方式。参数为mapping或者iteralbe,只能传入一个值。

字典可以通过索引创建新,而value,而list不可以。

1
2
>>> dict.fromkeys(range(32),'赞')
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞', 16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞', 31: '赞'}

get方法不会报KeyError。

清空字典用clear(),比赋空值{}更推荐。

1
2
3
4
5
6
7
8
9
10
11
12
>>> a = {'name':'lee'}
>>> b =a
>>> a.clear()
>>> b
{}
>>> a = {'name':'lee'}
>>> b =a
>>> a = {}
>>> b
{'name': 'lee'}

copy的话会改变对象的id,重新一份。

pop(key)

setdefault

集合

{1,2,3,4,5}表示集合

set去重复后的顺序是无序的

frozenset()工厂函数

文件

f.writelines(seq),seq为可迭代对象

makedirs递归创建多层目录,如果该目录已存在则抛出异常。

removedirs(path)递归删除目录,从子目录到父目录逐层尝试删除,目录非空报异常。

os.path获取文件详细信息,getctime 、getatime,getmtime,返回浮点数。可用time.localtime()或time.gmtime() 世界标准时转换、

异常

except OSError as reason,打印reason时要把它强制转为字符

for和while能搭配else,当循环完成后,就能怎样,干不完就别想怎样

字符

startswith通过()调用

1
2
3
4
5
>>> 'http://google.com'.startswith('http')
True
# 而不是以下面的方式!
>>> 'http://google.com'.startswith == 'http'
False

re

有歧义的情况下最好把各部分()起来

1
2
3
4
(//|www\.)(\w+)[.] 和 //|www\.(\w+)[.] 的结果完全不一样
https://www.cnet.com
www.xakep.ru
http://google.com

对象

对象(类) = 静态的属性 + 动态的方法

pass起占位符的作用

多态 :不同对象对同一方法响应不同行动

类的属性前加上2个下划线,则通过Class.__attr无法调用,被称为伪私有

1
2
3
4
5
6
>>> class Person:
__name = '小甲鱼'
>>> p = Person()
>>> p._Person__name # 通过_class__attr隐性访问
'小甲鱼'

组合是指把几个横向关系的类,没有继承关系的类放到新类里。在新类里通过self.class1 = Class()组成。

属性名和方法名相同时,会冲突。属性命名用名词,方法命名用动词。

通过dict调用类的属性。