跳至正文
Wener Notes

Python Reference

约 2 分钟阅读
标签:参考资料
abbr.stand formeaning
dunderdouble underscore双下划线
pycPython Compiled编译后的 Python 代码
GILGlobal Interpreter Lock全局解释器锁
cocode object编译后的代码对象
dunderfor
__init__构造函数
__str__字符串表示
__repr__官方字符串表示
__len__长度
__getitem__索引
__setitem__设置索引
__delitem__删除索引
__iter__(self)可迭代
__next__(self)下一个
__contains__包含
__call__可调用
Method
__getattr__获取属性
__getattribute__获取属性
Math
__add__加法
__sub__减法
__mul__乘法
python
source_code = "result = a + b"

# 手动将字符串编译成一个代码对象
code_obj = compile(source_code, filename='<string>', mode='exec')

# 准备一个执行环境(命名空间)
namespace = {'a': 10, 'b': 20}

# 执行代码对象
exec(code_obj, namespace)

# 从命名空间中获取结果
print("Result: ",namespace['result'])  # 输出: 30

# 打印代码对象的类型
print(f"Type of __code__: {type(code_obj)}\n")

# 查看代码对象的所有属性
print("Attributes of the code object:")
for attr in dir(code_obj):
    if attr.startswith('co_'):
        print(f"  - {attr}: {getattr(code_obj, attr)}")


import dis
dis.dis(code_obj) # 反汇编
text
Type of __code__: <class 'code'>

Attributes of the code object:
  - co_argcount: 0
  - co_cellvars: ()
  - co_code: b'e\x00e\x01\x17\x00Z\x02d\x00S\x00'
  - co_consts: (None,)
  - co_filename: <string>
  - co_firstlineno: 1
  - co_flags: 64
  - co_freevars: ()
  - co_kwonlyargcount: 0
  - co_lnotab: b''
  - co_name: <module>
  - co_names: ('a', 'b', 'result')
  - co_nlocals: 0
  - co_posonlyargcount: 0
  - co_stacksize: 2
  - co_varnames: ()

dis

text
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 BINARY_ADD
              6 STORE_NAME               2 (result)
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
  • Dunder Methods
    • __init__
  • Code Object
    • 编译后的对象
    • pyc
    • func.__code__

关联信息

反向链接、本文链接的其他页面和外部资料。

参考资料

其他外链3 条
最近更新commit 0892106编辑