11

python中id转换为object instance

 3 years ago
source link: http://blog.ilibrary.me/2020/02/29/python%E4%B8%ADid%E8%BD%AC%E6%8D%A2%E4%B8%BAobject-instance
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
欢迎转载,请支持原创,保留原文链接:blog.ilibrary.me

functools.lru_cache

python有个内置的functools.lru_cache, 这是一个基于lru的cache,作用于函数或者类方法上. 该装饰器会根据参数值来缓存方法调用的结果。

但是,被装饰的方法的参数必须是hashable的。如果是强类型的, 改类型需要实现__hash__()方法.

基础类型(int, long, float, bool, ),方法, string, tuple, 都是hashable的.

下面的代码是合法的。

t = (3,2,"aaa",)

e = {d: "a", 
dir: 1, 
"str": 3, 
str: 4
}

可以通过下面的代码获取内置类型

dir(globals()['__builtins__'])

如果传了不可hashable的参数,那么该装饰器会不工作。

一个解决办法是传递对象的id(object)

Ctypes.cast

import ctypes
a = "hello world"
print(ctypes.cast(id(a), ctypes.py_object).value) # 注意ctypes.cast返回的是一个py_object, py_object.value指向原始的对象.
扫描二维码分享到微信朋友圈Loading...Please waitqrcode.php?url=%2F2020%2F02%2F29%2Fpython%25E4%25B8%25ADid%25E8%25BD%25AC%25E6%258D%25A2%25E4%25B8%25BAobject-instance

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK