python 使用备忘
2022-11-07 tech python 3 mins 1276 字
最近重新拿起 python,这里零碎地记录一下内容
-
python 官方手册 - class 基本使用
class Circle(object): def __init__(self, R): self.r = R circle1 = Circle(1) print(circle1.r)
-
获得应用变量类型
type()
-
美化 class 的 print 输出
Python dictionary from an object’s fields
先将 class 转成 dict,再用 yaml.dump 转换,同时注意中文乱码问题:
class Project: xxx project = Project(xxx) projectDict = vars(project) print(yaml.dump(projectDict,allow_unicode=True))
-
创建字典 Dict
dict = {"key":"value"}
-
确认dict中是否有key:
Check if a given key already exists in a dictionary
if "key1" in d: print("xxx")
-
日期操作
import datetime time_now = datetime.datetime.now() t1=datetime.datetime.strptime("20221107","%Y%m%d") t2=t1.replace(month=t1.month - 1).strftime("%Y-%m-%d")
参考资料
- How to pretty print nested dictionaries?
- Python Yaml 写入中文乱码的问题
- Python中time和datetime的区别
- https://docs.python.org/zh-cn/3.10/tutorial/classes.html
- Python入门 类class 基础篇
- Sanic
- Python Programming - Creating an Array of Class Objects
- 基本类型的用法:https://www.runoob.com/python/python-variable-types.html
- Python实例方法、静态方法和类方法详解(包含区别和用法)