类
1、私有参数
class people: #定义基本属性 name = '' age = 0 #定义私有属性,私有属性在类外部无法直接进行访问 __weight = 0 #定义构造方法 def __init__(self,n,a,w): self.name = n self.age = a self.__weight = w def speak(self): print(f"{self.name} 说: 我{self.age}岁,体重{self.__weight}kg") t1 = people("tom", 20, w=100) t1.speak()
2、私有方法
class Site: def __init__(self, name, url): self.name = name # public self.__url = url # private def who(self): print('name : ', self.name) print('url : ', self.__url) def __foo(self): # 私有方法 print('这是私有方法') def foo(self): # 公共方法 print('这是公共方法') self.__foo() x = Site('Python', 'www.irvingao.com') x.who() # 正常输出 x.foo() # 正常输出 x.__foo() # 报错
3、继承
class people: #定义基本属性 name = '' age = 0 __weight = 0 def __init__(self,n,a,w): self.name = n self.age = a self.__weight = w def speak(self): print("%s 说: 我 %d 岁。" %(self.name,self.age)) class student(people): #student为子类,people为父类 grade = '' def __init__(self,n,a,w,g): #调用父类的构函 people.__init__(self,n,a,w) self.grade = g #覆写父类的方法 def speak(self): print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade)) s = student('ken',10,60,3) s.speak()
4、super
class Parent: # 定义父类 def myMethod(self): print('调用父类方法') class Child(Parent): # 定义子类 def myMethod(self): print('调用子类方法') c = Child() c.myMethod() super(Child, c).myMethod()
requirements文件
# 方法一 # 添加环境中的所有包 pip install -r requirements.txt pip freeze > requirements.txt # 方法二 # 添加用到的包 pip install pipreqs pipreqs ./ --encoding=utf8
# 安装所有的包 pip install -r requirements.txt -i https://pypi.douban.com/simple
配置文件
ini
import configparser # 创建一个 configparser 对象 config = configparser.ConfigParser() # 读取 INI 文件 config.read('config.ini') # 获取一个配置节 section = config['SectionName'] # 获取某个键的值 key_value = section['key_name'] # 改变某个键的值 section['key_name'] = 'new_value' # 写回文件 with open('config.ini', 'w') as configfile: config.write(configfile)
json
# loads操作的是字符串 # load操作的是文件流 # json.dumps()是把python对象转换成json对象的一个过程,生成的是字符串。 # json.dump()是把python对象转换成json对象生成一个fp的文件流,和文件相关。
‣
toml
[mysql] host = "127.0.0.1" user = "root" port = 3306 database = "test" [mysql.parameters] pool_size = 5 charset = "utf8" [mysql.fields] pandas_cols = [ "id", "name", "age", "date"] >>> import toml >>> import os >>> from pprint import pprint >>> cfg = toml.load(os.path.expanduser("~/Desktop/config.toml")) >>> pprint(cfg) {'mysql': {'database': 'test', 'fields': {'pandas_cols': ['id', 'name', 'age', 'date']}, 'host': '127.0.0.1', 'parameters': {'charset': 'utf8', 'pool_size': 5}, 'port': 3306, 'user': 'root'}}
yaml
mysql: host: "127.0.0.1" port: 3306 user: "root" password: "123456" database: "test" parameter: pool_size: 5 charset: "utf8" fields: pandas_cols: - id - name - age - date >>> import os >>> from pprint import pprint >>> >>> with open(os.path.expanduser("~/config.yaml"), "r") as config: ... cfg = yaml.safe_load(config) ... >>> pprint(cfg) {'mysql': {'database': 'test', 'fields': {'pandas_cols': ['id', 'name', 'age', 'date']}, 'host': '127.0.0.1', 'parameter': {'charset': 'utf8', 'pool_size': 5}, 'password': '123456', 'port': 3306, 'user': 'root'}}
Python虚拟环境
虚拟环境需要已经安装了相应版本的解释器才可创建
1、windows创建虚拟环境
# 指定版本为3.12 py -3.12 -m venv .venv
2、Linux、Mac创建虚拟环境
# 指定版本为3.12 python3.12 -m venv .venv
3、其他相关命令
# 安装python winget install Python.Python.3.11 # 查看所有已安装的 Python 版本 py -0
4、调用不同的python版本
D:\111\FILES\1Python解释器>py -0 -V:3.12 * Python 3.12 (64-bit) -V:3.9 Python 3.9 (64-bit) -V:ContinuumAnalytics/Anaconda37-64 Anaconda 5.3.0 # 调用并运行 py -3.12 -m pip install pandas
函数仅执行一次
1、使用全局变量
has_run = False def run_once(): global has_run if not has_run: print("这段代码只执行一次") has_run = True else: print("代码已经执行过了") run_once() run_once()
2、定义装饰器
from functools import wraps def run_once_decorator(func): has_run = False @wraps(func) def wrapper(*args, **kwargs): nonlocal has_run if not has_run: has_run = True return func(*args, **kwargs) else: print("代码已经执行过了") return wrapper @run_once_decorator def run_once(): print("这段代码只执行一次") run_once() run_once()
3、使用单例模式
单例模式确保一个类的实例只会被初始化一次,可以借此实现某段代码只运行一次的功能。
class RunOnce: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls) print("这段代码只执行一次") return cls._instance # 多次实例化只会触发一次代码执行 obj1 = RunOnce() obj2 = RunOnce()
4、线程锁
在多线程环境下,可以使用
threading
模块的锁机制来确保代码只运行一次。import threading lock = threading.Lock() has_run = False def run_once(): global has_run with lock: if not has_run: print("这段代码只执行一次") has_run = True run_once() run_once()
5、内置模块
atexit
atexit.register
会在程序结束时确保注册的函数执行一次import atexit def run_once(): print("这段代码只执行一次") atexit.register(run_once) print("123")
代码仅执行一次
1、函数属性
利用函数的静态属性来记录代码是否执行过
def some_function(): if not hasattr(some_function, "has_run"): print("这几行代码只执行一次") some_function.has_run = True # 设置标志 # 其他代码(每次都会执行) print("其他代码") some_function() some_function()
2、使用全局变量
has_run = False def some_function(): global has_run if not has_run: print("这几行代码只执行一次") has_run = True # 其他代码(每次都会执行) print("其他代码") some_function() some_function()
3、使用类属性
class CodeRunner: has_run = False def some_function(): if not CodeRunner.has_run: print("这几行代码只执行一次") CodeRunner.has_run = True # 其他代码(每次都会执行) print("其他代码") some_function() some_function()
4、线程锁
import threading lock = threading.Lock() has_run = False def some_function(): global has_run with lock: if not has_run: print("这几行代码只执行一次") has_run = True # 其他代码(每次都会执行) print("其他代码") some_function() some_function()
5、
atexit
注册import atexit has_run = False def initialize_once(): global has_run if not has_run: print("这几行代码只执行一次") has_run = True atexit.register(initialize_once) def some_function(): initialize_once() print("其他代码") some_function() some_function()
单独写
atexit.register(initialize_once)
会在代码结束前执行,如果调用了initialize_once()
就正常按函数执行6、缓存机制
from functools import lru_cache @lru_cache(maxsize=1) def run_once(): print("这几行代码只执行一次") def some_function(): run_once() print("其他代码") some_function() some_function()
文本超长换行(字符串)
(1)textwrp.fill()自动换行
import pprint import textwrap data = "long string~~~" wrapped_message = textwrap.fill(data, width=50) # 每行最多 50 字符 pp = pprint.PrettyPrinter(width=50) pp.pprint(wrapped_message)
(2)textwrap.wrap()并转换成列表
wrapped_message_list = textwrap.wrap(data, width=50) pp.pprint({"message": wrapped_message_list})
(3)重写PrettyPriinter方法处理长字符串
class MyPrettyPrinter(pprint.PrettyPrinter): def format(self, obj, context, maxlevels, level): if isinstance(obj, str) and len(obj) > 50: obj = textwrap.fill(obj, width=50) return super().format(obj, context, maxlevels, level) pp = MyPrettyPrinter(width=50) pp.pprint({"message": data})
异常
其中Exception为超类,子类如下:
ValueError
—— 传递的参数类型正确,但值不符合要求
TypeError
—— 传递的参数类型错误
IndexError
—— 列表、元组、字符串索引超出范围
KeyError
—— 字典中找不到指定的键
ZeroDivisionError
—— 试图除以零
FileNotFoundError
—— 文件未找到
文件写入刷新
with open() as f: # 写入代码 f.flush() # 避免程序暂停后的缓存影响,刷新 os.fsync(f.fileno()) # 强行写入磁盘,但可能会有延迟
偏函数
偏函数(Partial Functions)是通过固定函数的某些参数,从而创建一个新的函数。这样可以减少函数调用时需要传递的参数数量。
from functools import partial def multiply(x, y): return x * y # 创建新函数,将multiply的第一个参数固定为2 double = partial(multiply, 2) # 现在只需要传递一个参数 print(double(5)) # 输出:10 print(double(3)) # 输出:6
常见用途:
- 简化函数调用,通过预设某些参数值
- 转换函数接口,使其适应特定的API要求
- 创建特定场景的专用函数
# 示例:转换数字的进制 from functools import partial # int函数可以接受base参数指定进制 hex_to_int = partial(int, base=16) bin_to_int = partial(int, base=2) print(hex_to_int('a')) # 输出:10 print(bin_to_int('1010')) # 输出:10