Python学习笔记2
本文最后更新于 2024年7月31日 上午
小刀笔记
单例模式
- 使用__new__方法
1 |
|
- 装饰器版本
1 |
|
- import方法
1 |
|
- 共享属性
创建实例时把所有实例的__dict__指向同一个字典,这样它们具有相同的属性和方法.
1 |
|
协程
协程是进程和线程的升级版,进程和线程都面临着内核态和用户态的切换问题而耗费许多切换时间,而协程就是用户自己控制切换的时机,不再需要陷入系统的内核态.
Python里最常见的yield就是协程的思想。
__new__和__init__的区别
- __new__是一个静态方法,而__init__是一个实例方法.
- __new__方法会返回一个创建的实例,而__init__什么都不返回.
- 只有在__new__返回一个cls的实例时后面的__init__才能被调用.
- 当创建一个新实例时调用__new__,初始化一个实例时用__init__.
迭代器和生成器
Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly.
It is just the same except you used () instead of []
To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky :-)
Understanding the inner mechanisms of iteration
Iteration is a process implying iterables (implementing the iter() method) and iterators (implementing the next() method). Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.
闭包
当一个内嵌函数引用其外部作作用域的变量,我们就会得到一个闭包. 总结一下,创建一个闭包必须满足以下几点:
- 必须有一个内嵌函数
- 内嵌函数必须引用外部函数中的变量
- 外部函数的返回值必须是内嵌函数
lambda函数
需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数.
1 |
|
Python函数式编程
filter 函数的功能相当于过滤器。
map函数是对一个序列的每个项依次执行函数.
reduce函数是对一个序列的每个项迭代调用函数,下面是求3的阶乘:
1 |
|
Python的is
Python 中的对象包括3要素,id(唯一标示), type(类型), value(值)
is 用来判断,a 对象是否是 b 对象,用id来判断
== 用来判断 a 对象的值是否与 b的值相同
Python2和3的区别
print 函数
print语句没有了,取而代之的是print()函数。
Unicode
Python 2 有 ASCII str() 类型,unicode() 是单独的,不是 byte 类型。
现在, 在 Python 3,我们最终有了 Unicode (utf-8) 字符串,以及一个字节类:byte 和 bytearrays。
除法运算
在python 3.x中/除法不再这么做了,对于整数之间的相除,结果也会是浮点数。
//地板除一致 -1//2=-1
不等运算符
Python 2.x中不等于有两种写法 != 和 <>
Python 3.x中去掉了<>, 只有!=一种写法
raw_input()和input()
python3.x中raw_input()和input()进行了整合,去除了raw_input(),仅保留了input()函数,其接收任意任性输入,将所有输入默认为字符串处理,并返回字符串类型。
map、filter 和 reduce
在Python 3.x中,它们从函数变成了类,其次,它们的返回结果也从当初的列表成了一个可迭代的对象
python中self和cls的区别
- self表示一个具体的实例本身。
- cls表示这个类本身。
pythonic
1 |
|