谁能给我讲讲 python 托管?
本帖最后由 xihuanqiqi 于 2013-10-15 18:03:01 编辑 主要是在研究Python Cookbook的第六章,然后遇到一节:继承的替代方案-自动托管,对自动托管不是很懂。。。。然后百度谷歌,不知道是不是我太笨,搜不到太多资料。。哪位python大神给小妹讲解下,感激不尽。。。
from sets import Set as set
class ROError(AttributeError):pass
class ReadOnly:#经典类
mutators = {
list:set('''__delitem__ __delslice__ __iadd__ __imul__ __setitem__ __setslice__ append extend insert pop remove sort'''.split()),
dict:set('''__delitem __setitem__ clear pop popitem setdefault update'''.split())
}
def __init__(self,o):
object.__setattr__(self,'_o',o)
object.__setattr__(self,'_no',self.mutators.get(type(o),()))
def __setattr__(self,name,value):
raise ROError,"Can't set attr %r on RO object" % name
def __delattr__(self,name):
raise ROError,"Can't del attr %r from RO object" % name
def __getattr__(self,name):
if name in self._no:
raise ROError,"Can't get attr %r from RO object" % name
return getattr(self._o,name)
小妹想问问:_o和_no到底是啥意思。。
[解决办法]
书上接下来应该会有例子,看看例子,再想想例子中的代码会怎么执行,也可以帮助你理解代码。
下面是一个例子:
restricted = ReadOnly([])
调用ReadOnly.__init__, 则 o is [], _o will be [], type(o) will be ??, _no will be ??