根据内存地址指定的对象获取

根据内存地址指定的对象获取

普通变量获取

 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

pickle序列

只能在python语言中使用,支持python的所有的数据类型,函数,实例化对象等等。

与网络相关

 import pickle
 dic = {'username': 'abc', '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='rb') as f1:
     ret = pickle.load(f1)
     ret()
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值