如何创建自己的自定义容器?
class Empty(object):
def __init__(self, **kwargs):
object.__setattr__(self, '_obj', kwargs)
def __getattribute__(self, name):
obj = object.__getattribute__(self, '_obj')
try:
return obj[name]
except KeyError:
cls_name = object.__getattribute__(self, '__class__').__name__
raise AttributeError(
"'%(cls_name)s' object has no attribute '%(name)s'" % locals())
def __setattr__(self, name, val):
obj = object.__getattribute__(self, '_obj')
obj[name] = val
def __getitem__(self, key):
return getattr(self, key)
def __setitem__(self, key, val):
return setattr(self, key, val)
用法:
e = Empty(initial='optional-value')
e.initial
# 'optional-value'
e.val = 'foo'
e.val
# 'foo'
e.bad
# AttributeError: 'Empty' object has no attribute 'bad'
setattr(e, 'user', 'jdi')
e.user
# 'jdi'
e['user']
# 'jdi'
# note that you dont even see anything when you dir()
dir(e)
# []
# and trying to access _obj is protected
e._obj
#AttributeError: 'Empty' object has no attribute '_obj'
# But you could even set your own _obj attribute
e._obj = 1
e._obj
# 1
它会将所有内容存储在_obj字典下,因此您基本上可以获得一个与实际实例属性不冲突的干净空间.