-1
以this question爲指針類,假設存在類似下面的類:實現_del_方法與__getattribute__重寫
class Container(object):
def __init__(self, **kwargs):
self._meta = defaultdict(lambda: None)
for attr, value in kwargs.iteritems():
self._meta[attr] = value
def __getattr__(self, key):
try:
return self._meta[key]
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, value):
if key in ('_meta', '_hasattr'):
super(Container, self).__setattr__(key, value)
else:
self._meta[key] = value
這允許以下行爲:
c = Container()
c.a = 1
print(c.a) # 1
print(c.b) # None
問題:實施運營商的最佳方式是什麼?以下工作原理:
# Should delete the value of a from Container._meta
del c.a
當然,人們可以明顯地實施的方法一樣,
def _delete(self, key):
...
但是,有沒有辦法再使用python的運營商做到這一點?
爲什麼這個downvoted? – viksit