Python方法合集
方法合集
方法/模块 | 作用 | 使用示例 |
---|---|---|
SimpleHTTPServer | 临时搭建一个文件共享平台 | 在目标目录下执行 python -m SimpleHTTPServer 端口号 浏览器可以通过http://IP:端口号/ 访问 |
ConfigParser | 配置文件解析 | |
dict
方法/模块 | 作用 | 使用示例 |
---|---|---|
dict.has_key(key) | 查看字典中是否有这个key,如果有返回true,反之false | |
addict模块 | 对字典的k和v进行快速获取和设置 | from addict import Dict body = Dict() |
字符串
方法/模块 | 作用 | 使用示例 |
---|---|---|
strip() | 移除字符串头尾的指定字符 | str.strip(’\r’) |
format() | 格式化字符串 | “{} {}”.format(“hello”, “world”) # 不设置指定位置,按默认顺序 "{1} {0} {1}".format(“hello”, “world”) # 设置指定位置 |
replace() | 字符串的替换 | str.replace(‘a’,b) # 把字符串中的a替换成b |
round():保留浮点数
示例:
f = 3.1415926
print round(f,2) # 保留小数位前两位
os模块应用
命令 | 命令详解 |
---|---|
os.path.join(pathname1,pathname2) | 用于把多个地址合并成一个 |
os.getcwd() | 获取当前所在目录 |
os.path.abspath(“path”) | 返回绝对值路径 |
getattr() :用于返回一个对象属性值
语法:
getattr(object, name[, default])
object -- 对象。
name -- 字符串,对象属性。
default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
返回值:
返回对象属性值。
示例:
>>>class A(object):
... bar = 1
...
>>> a = A()
>>> getattr(a, 'bar') # 获取属性 bar 值
1
>>> getattr(a, 'bar2') # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3) # 属性 bar2 不存在,但设置了默认值
3
hasattr() :判断是否有对应的属性
语法:
hasattr(object,name)
object -- 对象
name -- 字符串,属性名
返回值:
如果对象有该属性返回 True,否则返回 False。
示例:
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print(hasattr(point1, 'x')) # 返回True
locals()
locals() 以字典类型返回当期位置的全部局部变量
示例:
>>>def runoob(arg): # 两个局部变量:arg、z
... z = 1
... print (locals())
...
>>> runoob(4)
{'z': 1, 'arg': 4} # 返回一个名字/值对的字典
mysql课外知识
select * from books\G; 格式化查询
装饰器合集
自定义装饰器
def myfunc(func):
def wrap(*args,**kwargs):
return func(*args,**kwargs)
return wrap
@method_decorator
#django提供一个特殊的装饰器,@method_decorator(logging_check)
# function dec 函数式装饰器
# method dec 方法装饰器
#method_decorator 将自定义的 function dec 转换成 method dec
可以把函数式装饰器套进@method_decorator中,这样函数式装饰器可以装饰类方法和普通方法
爬虫spider
ignore:解码过程中遇到不能识别的字符直接忽略
示例:
html = requests.get(url=url, headers=headers).content.decode('gb2312', 'ignore')