python3 获取内存地址对象
普通变量获取
import ctypes
value = 'hello world' # 定义一个字符串变量
address = id(value) # 获取value的地址,赋给address
get_value = ctypes.cast(address, ctypes.py_object).value # 读取地址中的变量
print(address,get_value)
2390895579248 hello world
此处借鉴自:python通过内存地址获取数据 - 有腹肌的猿 - 博客园 (cnblogs.com)
以下为自己测试所得:
对象类获取 (其中有几种情况需要注意)
import ctypes
class fun:
def __init__(self):
self.abc = 123
def test(self):
print('abc')
aaa = fun()
address = id(aaa)
get_value = ctypes.cast(address, ctypes.py_object).value
print(address, dir(get_value)) # 这里通过dir查看改对象中的所有可调用的属性和方法,现在的get_value = aaa
1390847666312 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'__weakref__', 'abc', 'test']
注意:
若 address = id(fun()) # 这样是获取不到对象数据的 显示为空
2、address = id(fuc) # 这里根据id获取的 get_value == fun
-
只能在python语言中使用,支持python的所有的数据类型,函数,实例化对象等等。
-
import pickle
dic = {'username': '太白', 'password': 123}
# 序列化 直接转化成了一个bytes类型
b1 = pickle.dumps(dic)
# print(b1)
# 反序列化
d1 = pickle.loads(b1)
print(d1,type(d1)) -
与文件相关
import pickle
# l1 = ['barry', 123, (22, 33, 44), True]
# with open('register',mode='wb') as f1:
# pickle.dump(l1,f1)
# with open('register',mode='rb') as f2:
# ret = pickle.load(f2)
# print(ret,type(ret))
# 多个数据对象写入
dic1 = {'name':'oldboy1'}
dic2 = {'name':'oldboy2'}
dic3 = {'name':'oldboy3'}
# with open('register',mode='wb') as f1:
# pickle.dump(dic1,f1)
# pickle.dump(dic2,f1)
# pickle.dump(dic3,f1)
# with open('register',mode='rb') as f1:
# # ret = pickle.load(f1)
# # print(ret)
# # ret = pickle.load(f1)
# # print(ret)
# # ret = pickle.load(f1)
# # print(ret)
# while 1:
# try:
# print(pickle.load(f1))
# except Exception:
# break
-
还可以存储对象
# 可以存储对象
def func():
print('in func')
import pickle
with open("t1",mode='wb') as f1:
pickle.dump(func,f1)
import pickle
with open("t1", mode='rb') as f1:
ret = pickle.load(f1)
ret()
-