Python

字典

key不存在,报错场景

复制代码

dic={} dic['a'] # 报错 dic.get('a') # 不报错 返回None dic['a']=1 # 不报错,直接创建a=1的键值对 print(dic)

查看源码

cmd+click,蓝色面板里面显示了python内置是怎么实现字典的get,但是没有底层源码

方法入参

TypeVar来自typing.TypeVar,用于泛型占位。

复制代码

KT = TypeVar("KT") # 入参是name VT = TypeVar("VT")

用法举例

复制代码

from typing import TypeVar T = TypeVar('T') def demo(x: T) -> T: return x

  • "/"

    入参按照顺序传入get(k1) ✅,不允许写成k1=v1传入 get(k1=v1)❌

python的内置函数源码注册在CPython中

CPython源码:https://github.com/python/cpython/blob/main/Objects/dictobject.c#L3703

CPython是Python的解释器,由C语言实现。Python内置的函数,例如dict.get(k)的源码注册在CPython中,所以总说Python的底层是C语言。

调用顺序

.py - CPython 编译成中间码 - CPython 解释器 执行+调用c层函数

类比java : .java - jvm编译成.class中间码 - jvm解释器执行

复制代码

_PyDict_Subscript(PyObject *self, PyObject *key) { Py_hash_t hash = _PyObject_HashFast(key); if (hash == -1) { dict_unhashable_type(self, key); return NULL; } return _PyDict_SubscriptKnownHash(self, key, hash); }

Argument clinic机制

c层开发者利用Argument clinic工具,实现简单声明-> 代码生成。

复制代码

/*[clinic input] demo.add x: int y: int = 1 / Return x + y. [clinic start generated code]*/

Hashable

字典的key必须是hashable的。作为key的变量,在其生命周期,不会变。比如str,int等,但是数组1,2不行,作为key的话,内容发生变化,hash会发生变化,导致无法快速查找,视为unhashable。

相关推荐
cup1118 分钟前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi002 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵4 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf5 小时前
Agent 流程编排
后端·python·agent
copyer_xyf5 小时前
Agent RAG
后端·python·agent
copyer_xyf5 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf6 小时前
Agent 记忆管理
后端·python·agent
星云穿梭21 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵21 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏