# web-python-2025 **Repository Path**: leslie43/web-python-2025 ## Basic Information - **Project Name**: web-python-2025 - **Description**: Learning Python Base knowledge - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-06-30 - **Last Updated**: 2025-07-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: Python ## README ### 安装扩展 🏀 - `Black Formatter` ### 配置格式化 🏀 ```json "[python]": { "editor.defaultFormatter": "ms-python.black-formatter", "editor.formatOnSave": true }, ``` ### snippets ```py print("-------------xxxxx----------------------") ``` ### 可变类型 vs 不可变类型 - 可变类型: list, dict, set - 不可变类型: tuple, str, int, float, bool, None ### 深浅拷贝: 针对于可变类型 - 浅拷贝: 拷贝最外层的对象, 内部的元素只拷贝了一个引用 - 深拷贝: 拷贝所有的对象, 包括内部的元素 ### 函数返回多个值 - 以元组的形势出现 ```py def doSomething(): return "1", 2, [3, 4] ``` - 调用函数 ```py a, b, c = doSomething() print(a, b, c) # 1 2 [3, 4] ``` ### 返回值 - 函数的返回值可以是任意类型 - 函数的返回值可以是多个 - 函数的返回值可以是没有, 即返回 `None` # 参数 及 类型 - 形参: 定义的时候的参数 - 实参: 调用的时候的参数 - 必备参数 默认参数 可变参数 | 关键字参数 ```py # - 默认参数: def minus(a, b=10, c=100): print(f"a, b, c is {a,b,c}") # a, b, c is (1, 10, 100) minus(1) # - 可变参数: 可以传递任意多个参数, 以元组的形式出现 def multiple(a, *args): print(a) # 1 print(args) # (2, 3, 4, 5) multiple(1, 2, 3, 4, 5) # - 关键字参数: 可以传递任意多个参数, 以字典的形式出现 # - 传值的时候用 key = value. # - 扩展函数的功能 def keyword(a, **kwargs): print(a, kwargs) # 1 {'name': 'leslie', 'age': 19} keyword(1, name="leslie", age=19) ``` ### 函数嵌套定义 ```py # 函数嵌套定义 def study(): print("Study hard 1") def course(): # study() # 调用外层的函数 dead loop print("Python") course() study() ``` ### 作用域例子 - global - 其功能是在函数内部引用或修改全局变量.要是在函数内部直接给一个变量赋值, 该变量会被默认视为局部变量, 除非使用 global 关键字进行声明. - 当在函数内部需要修改全局变量的值时, 必须使用 global 关键字 - 若只是读取全局变量的值, 而不进行修改, 则可以不使用 global 关键字. ```python count = 0 # 这是一个全局变量 def increment(): global count # 表明要使用全局变量 count count += 1 # 对全局变量进行修改 increment() print(count) # 输出结果为 1 ``` ### nolocal - `nolocal`: 用来声明外层的局部变量, 只能在嵌套函数中使用,在外部函数先声明,内部函数进行nolocal声明 - `nolocal`: nonlocal 主要用于嵌套函数中, 它只能引用外层函数的变量, 不能引用全局变量 - `nolocal`: 只有当需要修改外层变量的值时, 才需要使用 nonlocal 关键字. ```py def outer(): a = 5 # 外部函数的局部变量 print(f"outer a {a}") # 5 def inner(): nonlocal a # 声明要修改外部函数的变量 a = 20 print(f"inner a {a}") # 20 def inner2(): nonlocal a a = 30 print(f"inner2 a {a}") # 30 inner2() inner() print("outer", a) # 输出 outer 30, 外部变量已被修改 outer() print(f"global a {a}") # 10 nolocal 不会影响全局变量 ``` ### nolocal global 的错误例子 ```py #### 1111111 x = 10 def wrong(): x += 1 # 会引发 UnboundLocalError 错误 print(x) wrong() #### 222222222 x = 10 def test(): nonlocal x # 会引发 SyntaxError 错误,因为 x 是全局变量 x += 1 ``` ### lambda - 代码少, 逻辑简单 ### 内置函数 - 大写字母开头表示内置常量名 - 小写字母开头表示内置函数名 ```py # ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] ``` ### 装饰器 - 装饰器: 不侵入代码修改代码功能 - 装饰器是一个函数,它可以在不修改原有函数代码的情况下,增加额外的功能 - 装饰器的原理就是将原来的函数当作闭包函数的外层实参传进去 ```python # 闭包形式的装饰器 def send(): print("Send message") def transfer_money(): print("Transfer money") def outer(fn:callable): # fn形参, 往里面传的是被装饰的函数名 def inner(): print("Login") # 执行被装饰的函数 fn() return inner ot1 = outer(send) ot1() ot2 = outer(transfer_money) ot2() ``` ## class ### 类的定义 - 可以直接用`.`的方式访问类的属性和方法 - 可以直接用`.`的方式添加属性和方法 ```py # 大驼峰命名 class Washer: height = 800 def wash(self): # self参数是类中的实例方法必须具备的 print("self",self) # self指向当前实例对象,当前调用该方法的实力对象 print("洗衣中...") Washer.width = 600 # 动态添加属性 print(Washer.height) print(Washer.width) # 实例化对象 washer1 = Washer() print(washer1) # <__main__.Washer object at 0x000002D6A8BE9550> washer1.wash() # self <__main__.Washer object at 0x000002D6A8BE9550> washer2 = Washer() print(washer2) washer2.wash() # self 代表对象本身, 当对象调用方法时, self指向当前对象 ``` ### self - `self` 是类中的实例方法必须具备的参数, 它指向当前调用该方法的实例对象 ### 类属性和实例属性的区别: 1. 类属性是类的所有实例共享的属性, 而实例属性是每个实例独有的属性. 2. 类属性可以通过类名直接访问, 而实例属性需要通过实例对象访问. 3. 类属性通常用于定义类的常量或默认值, 而实例属性用于存储每个实例的特定数据. ### 构造函数 - `__init__` 是类的构造函数, 用于初始化类的实例属性 ### 修改类属性 ```python class Person: name = "Leslie" p1 = Person p1.name = "Moon" print(p1.name) # Moon print(Person.name) # Moon p2 = Person() print(p2.name) # 输出: Moon ``` ### 私有方法属性和隐藏方法属性 - 私有属性和方法, 使用单下划线定义 - 弱封装 - 私有属性和方法, 使用 对象._attrName 访问 和 对象.funName() 访问 - 访问隐藏属性 - 可以通过别名: _ClassName__attribute - 类访问 print(Person._Person__age) - 29 不推荐 - 对象访问 print(p1._Person__age) # 30 不推荐 - 访问隐藏属性最好的方式是通过类的方法来访问 ```python class Person: name = "Leslie" __age = 29 # 私有属性: 只能在类的内部访问, 无法通过对象访问 def intro(self): print(f"{Person.name}的年龄是{self.__age}岁") return self.__age p1 = Person() age = p1.intro() print(age) ``` ### 调用父类方法的三种形式 - Dog.eat(self) # 继承父类的方式一: 调用父类Dog的bark方法 - 子类方法中: super().sleep() # 继承父类的方式二: 子类中调用super().父类方法() - 子类方法中: super(Dog, self).bark() # 继承父类的方式三: super(子类, self).父类方法() ### object - python 中所有的类都继承自 `object` 类 - 基类 -['__class__', - '__delattr__', - '__dir__', - '__doc__', - '__eq__', - '__format__', - '__ge__', - '__getattribute__', - '__gt__', - '__hash__', - '__init__', - '__init_subclass__', - '__le__', - '__lt__', - '__ne__', - '__new__', - '__reduce__', - '__reduce_ex__', - '__repr__', - '__setattr__', - '__sizeof__', - '__str__', - '__subclasshook__'] - python3中如果一个类没有继承任何类, 那么它默认继承自 `object` 类 ### 类的继承顺序 - 继承的顺序: Python会按照从左到右的顺序查找方法和属性 - 多个父类中有同名方法时, Python会按照继承顺序调用第一个找到的方法 Father 优先于 Mother 类 - 内置属性 __mro__: 用于查看类的继承顺序 - print(Child.__mro__) # 查看 Child 类的继承顺序 # (, , , ) - 如果调用的方法在自己的类中存在,则直接调用自己的方法;如果不存在, 则按照继承顺序查找父类的方法. ### 方法类型 - 实例方法: 需要实例化对象后才能调用, 需要传入实例对象作为第一个参数 - 实例方法内部访问实例属性, 方法内部可以通过类名, 类属性名来访问类属性 - 静态方法(`@staticmethod`): 方法内部不需要访问实例属性和类属性 - 静态方法不需要传入实例对象或类作为第一个参数, 可以直接通过类名调用 - 类方法(`@classmethod`): 方法内部只需要访问类属性, 需要传入类作为第一个参数 - 实例方法: 可以访问实例属性和类属性 - 静态方法/类方法: 不能访问实例属性, 只能访问类属性 - 类属性是公共的 - 实例属性是私有的, 只有通过实例对象才能访问 - 静态方法不需要访问类属性, 和类无关 ### 实例化过程 - 实例化过程: 首先执行` __new__`方法, 如果没有写`__new__()`, 默认调用object基类里提供的`__new__()`,返回一个实例对象 - 然后将实例对象作为参数,执行`__init__`方法 ### ` __new__` 和 `__init__` 的区别: -` __new__` 是一个静态方法, 用于创建对象的实例, 返回一个对象的引用 - `__init__` 是一个实例方法, 用于初始化对象的属性, 不返回任何值 ### 单例模式: 确保一个类只有一个实例,并提供一个全局访问点 - 单例模式: 一个特殊的类, 只存在一个实例 - 单例模式: 节省内存空间 - 单例模式: 线程安全问题 - 实现方式 1: 通过@classmethod装饰器实现 - 实现方式 2: 通过装饰器实现 - 实现方式 3: 通过重写 __new__方法实现 - 实现方式 4: 通过模块实现 ### 可迭代对象iterable 和 迭代器 iterator 的区别: - 凡是可以作用于for循环的都属于可迭代对象iterable - 凡事可以作用于 next()函数的都属于迭代器iterator ```python from collections.abc import Iterable,Iterator name = "leslie" isinstance(name, Iterable) # True, 字符串是可迭代对象 isinstance(name, Iterator) # False, 字符串不是迭代器对象 name2 = iter(name) # 创建迭代器对象,将可迭代对象转换成迭代器对象 isinstance(name2, Iterable) # True, 字符串是可迭代对象 isinstance(name2, Iterator) # True, 字符串是可迭代对象 ``` - 如果一个对象有 __iter__() 方法, 那么它就是可迭代对象 - 如果一个对象有 __iter__() 方法 和 __next__() 方法, 那么它就是迭代器对象 - 可迭代对象不一定是迭代器对象 - 迭代器对象一定是可迭代对象 ### 迭代器协议 - 对象必须提供一个next方法, 执行该方法要么返回迭代中的下一项, 要么引发 StopIteration异常, 来终止迭代 ### 可迭代对象, 迭代器, 生成器 - 范围: 可迭代对象 > 迭代器 > 生成器 - 可迭代对象: 实现了 python 迭代协议, 可以通过 for...in 循环遍历对象(list,dict,str) - 迭代器: 可以记住自己遍历的位置的对象,直观体现就是可以使用 next() 函数返回值. 迭代器只能往前不能往回, 抛出异常当取完最后一个值 - 生成器: 特殊的迭代器, 迭代器并不一定是生成器. 通过简单的方法写出迭代器的一种方式. - 范围: 可迭代对象(迭代器(生成器)) ### 进程 | 线程 | 协程 - 线程: CPU调度的基本单位 - 进程: 资源分配的基本单位 - 协程: 单线程内的多任务 - 对比 - 进程: 需要的资源最大 - 线程: 中间位置 - 协程: 需要的资源最小, 效率高 - 多线程适合IO密集型操作,文件操作,爬虫 - 多进程适合CPU密集型操作,科学计算, 视频解码 - 三者都可以完成多任务