包含标签 python 的文章

Python 枚举使用

from enum import Enum class Gender(Enum): male = 0 female = 1 print(Gender(0)) # Gender.male print(Gender(0).name) # female print(Gender(0).value) # 0 class EnumWithLabel(Enum): """ 允许带 label 的枚举类型, 参考: https://docs.python.org/zh-cn/3/library/enum.html#when-to-use-new-vs-init """ def __new__(cls, value, label): obj = object.__new__(cls) obj._value_ = value obj.label = label return obj class GenderWithLabel(EnumWithLabel): male = (0, "MAN") female = (1, "WOMAN") print(GenderWithLabel(0)) # GenderWithLabel.male print(GenderWithLabel(0).value) # 0 print(GenderWithLabel(0).label) # MAN class EnumWithDefault(Enum): """ 允许返回默认值的枚举类型, 不存在枚举值时不会报错 如果需要修改默认值则需要覆盖 new_default_obj 函数 """ @classmethod def _missing_(cls, value): new_member = cls.……

阅读全文

Mac 安装 mysqlclient

Python 版本 (venv) ➜ python --version Python 3.8.2 安装 brew install mysql export LDFLAGS="-L/usr/local/opt/openssl/lib" export CPPFLAGS="-I/usr/local/opt/openssl/include" pip install mysqlclient brew uninstall mysql ……

阅读全文

Python 中的else

if…else 最常见的 else if 1 > 0: pass else: pass for else for 循环中 只有 for 循环结束了才执行, 注意空循环也会执行 for i in range(3): print(i) else: print("end") # 0 # 1 # 2 # end for i in range(3): print(i) if i == 1: break else: print("end") # 0 # 1 try… else 这个就很好理解了, else 只会在 try 未发生任何异常的时候执行 finally 在所有状态下都会执行 try: 1 except Exception as e: print(e) else: print("else") finally: print("finally") # else # finally try: 1/0 except Exception as e: print(e) else: print("else") finally: print("finally") # division by zero # finally ……

阅读全文

python 异常处理

异常处理 def demo(): try: 1 / 0 except Exception as e: print(type(e)) #<class 'ZeroDivisionError'> 自定义异常 class CustomError(Exception): pass 异常链 class CustomError(Exception): pass def demo(): try: 1 / 0 except Exception as e: print(type(e)) #<class 'ZeroDivisionError'> raise CustomError() from e <class 'ZeroDivisionError'> Traceback (most recent call last): File "/Users/tiger/work/customer/dd.py", line 23, in demo 1 / 0 ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/tiger/work/customer/dd.……

阅读全文