Chinaunix首页 | 论坛 | 博客
  • 博客访问: 656745
  • 博文数量: 102
  • 博客积分: 2241
  • 博客等级: 大尉
  • 技术积分: 1670
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-08 10:08
文章分类

全部博文(102)

文章存档

2013年(6)

2012年(15)

2011年(81)

分类: Python/Ruby

2011-04-29 23:04:50



python class 隐藏类变量,解决访问 PyObject_New 对象进程崩溃问题


      近日在编写一个 python 扩展模块时,一个函数返回一个 PyObject_New 的对象,在对这个对象进行反射操作,如 dir, type 时,会出现非法内存访问,进程会崩溃。在使用 PyCrust 作为编辑调试器,经常需要查看 Namespace,这时不小心点到这个对象时,进程就会崩溃。

      另外,python 的类没有权限控制功能,使用双下划线名称命名私有成员,也仅是名称简单变换,不能解决这个问题。


      在 python New style class 中, 有一个方法 __getattribute__ 在访问每个类成员时都会被调用,可以覆盖这个方法对名称进行过滤,在发现要访问指定名称变量时检查有无特殊标志,没有则返回其它值,内部需要使用变量时加入特殊标志调用 __getattribute__ 方法


  1. class HideMemberClass(object):
  2.     def __init__(self):
  3.         self._db = 'this is real value'
  4.     def __getattribute__(self,name,flag=None):
  5.         if name=='_db' and flag != '*':
  6.             return '** No Access **'
  7.         return object.__getattribute__(self, name)
  8.     def getdb(self):
  9.         return self.__getattribute__('_db', '*')

  10. a=HideMemberClass()
  11. a._db
  12. '** No Access **'
  13. a.getdb()
  14. 'this is real value'


end.
阅读(4967) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~