- 前言
- 一、判断变量类型
- 二、json
- 三、抛出自定义异常
- 四、字符串转ASCII码
- 五、写入文件
- 六、数值转字符串
- 七、获取类名
- 八、获取当前函数的调用栈(行号)
- 九、打包模块
前言
记录Python常用的方法,持续更新
一、判断变量类型#判断var是否为int类型 isinstance(var, int) #判断var是否为元组中任意类型 isinstance(var, (str, int, list))二、json
import json
jsonPath; #json文件路径
jsonStr; #json字符串
#获取json对象
jsonObj = json.load(jsonPath) #加载json文件
jsonObj = json.loads(jsonStr) #解析json字符串
print(jsonObj['aaa']) #访问aaa成员
#将json存入文件
with open(jsonPath, "w+", encoding='utf-8') as f:
f.write(json.dumps(jsonStr, indent=4)) #indent代表缩进
with open(jsonPath, "w+", encoding='utf-8') as f:
json.dump(jsonStr, f, indent=4)
三、抛出自定义异常
class MemoryOutError(Exception):
def __init__(self, value) :
self.value = value
def __str__(self) :
return repr(self, value)
memorySize = 10
dataSize = 20
if dataSize > memorySize :
raise MemoryOutError('memory out')
四、字符串转ASCII码
import numpy as np str = 'hello world' ascii = np.fromstring(str, dtype=np.uint8) print(ascii)五、写入文件
path = './test.txt'
with open (path ,'w+') as fs:
fs.write("123456")
六、数值转字符串
number = 123456; string = str(number) print(string)
输出
123456七、获取类名
test = Test() ##先获取类,再通过__name__访问类名 print(type(test).__name__) print(test.__class__.__name__)
输出
Test Test八、获取当前函数的调用栈(行号)
def func1() :
print(str(sys._getframe().f_back.f_lineno))
print(str(sys._getframe().f_lineno))
def func2() :
func1()
func2()
参考:python函数调用栈
九、打包模块参考:python打包模块、python安装模块、python打包模块



