栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python使用笔记

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python使用笔记

文章目录
  • 前言
  • 一、判断变量类型
  • 二、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打包模块

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012490.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号