python只读属性怎么设置_在Python中设置只读属性?

尽管它的动态性,Python不允许猴子修补内置的类型,如文件.它甚至可以通过修改这种类型的__dict__来阻止你这样做 – __dict__属性返回包含在只读代理中的dict,因此对file.write和file.___ _ _ [‘write’]的赋值失败.至少有两个很好的理由:

> C代码期望文件内置类型对应于PyFile类型结构,并将file.write与内部使用的PyFile_Write()函数对应.

> Python实现对类型的属性访问的缓存,以加快方法查找和实例方法创建.如果允许这个缓存直接分配给类型类型,这个缓存将被破坏.

猴子补丁当然是允许在Python中实现的类,它可以处理动态修改.

但是,如果你真的知道你在做什么,你可以使用诸如ctypes这样的低级API来挂接实现并获得类型dict.例如:

# WARNING: do NOT attempt this in production code!

import ctypes

def magic_get_dict(o):

# find address of dict whose offset is stored in the type

dict_addr = id(o) + type(o).__dictoffset__

# retrieve the dict object itself

dict_ptr = ctypes.cast(dict_addr, ctypes.POINTER(ctypes.py_object))

return dict_ptr.contents.value

def magic_flush_mro_cache():

ctypes.PyDLL(None).PyType_Modified(ctypes.cast(id(object), ctypes.py_object))

# monkey-patch file.write

dct = magic_get_dict(file)

dct['write'] = lambda f, s, orig_write=file.write: orig_write(f, '42')

# flush the method cache for the monkey-patch to take effect

magic_flush_mro_cache()

# magic!

import sys

sys.stdout.write('hello world\n')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值