可变对象与不可变对象
对象有两种,“可更改”(mutable)与“不可更改”(immutable)对象。在python中,strings, tuples, 和numbers是不可更改的对象,而 list, dict, set 等则是可以修改的对象。(这就是这个问题的重点)
所以,传入函数的是不可变对象,那函数会自动复制一份a的引用:
1 | In [1]: a = 1 |
staticmethod和classmethod
classmethod
相当于c++中的重载构造函数,方便对类做自定义的初始化;
staticmethod
相当于类方法,独立于对象,被所有类对象都适用的通用方法。
1 | class Date(object): |
类变量、实例变量
实例的作用域里把类变量的引用改变了,就变成了一个实例变量,self.name不再引用Person的类变量name.
1 | In [8]: class Person: |
*args
and **kwargs
**kwargs
传递的是字典,
1 | In [17]: def fruit(*args): |
调用函数时解包:传递列表(或者元组)的每一项并把它们解包.注意必须与它们在函数里的参数相吻合
1 | In [19]: def de(a = 'a', b = 'b', c = 'c'): |
Property
用途1: 访问对象时,产生特殊行为
下例得优势在于,设置其中一个属性,对应需要更改的属性也随之改变。
1 | class Resistor(object): |
1 | # 1. |
用途2:实时计算
1 | """ |
动态属性
- 定义了
__getattr__
的类,动态加入对象查询时不存在的属性
1 | class lazyDB: |
1 | class LoggingLazyDB(lazyDB): |
1 | # 会在搜索对象属性后,调用__getattr__ |
1 | data.__dict__ |
1 | # 确保不会添加某些属性名 |
- 定义了
__getattribute__
的类,每次访问对象属性时都会触发
1 | class ValidatingDB: |
1 | data = ValidatingDB() |
- 使用
__setattr__
时,每次对属性赋值都会触发。
1 | class SavingDB: |
contextlib + with 实现可复用的try + finally
1 | def my_function(): |
1 |
|
自带函数
双端队列,在头部插入删除元素是常数时间复杂度,list
是线性复杂度。
1 | from collections import deque |
Wraps
- 用装饰器修饰函数,使得函数执行前后做一些事。
1 | ## work: 打印函数调用时,接收到的参数以及函数返回值。 |
partial
- 对函数上增加、替换额外参数
1 | from functools import partial |
cmp_to_key
Transform an old-style comparison function to a key function.
Used with tools that accept key functions (such as sorted()
, min()
, max()
, heapq.nlargest()
, heapq.nsmallest()
, itertools.groupby()
).
This function is primarily used as a transition tool for programs being converted from Python2 which supported the use of comparison functions.
A comparison function is any callable that accept two arguments, compares them, and returns a negative number for less-than, zero for equality, or a positive number for greater-than.
A key function is a callable that accepts one argument and returns another value to be used as the sort key.
1 | from functools import cmp_to_key |
format上格式控制!r
{!r}
与format()
配合使用,而%r
与%配合使用,二者不可以混合使用,否则会报错!
在str.format
中,!s
选择用于str
设置对象格式,而!r
选择repr
设置值格式。
解析csv中间没有空白
1 | with open("sample.csv", "w", newline="") as outfile: |
1 | CREATE TABLE `aof.aof_galileo_graph_info`( |