class ObjectDict(dict):
""" allows object style access for dictionaries """
def __getattr__(self, name):
if name in self:
return self[name]
else:
raise AttributeError('No such attribute: %s' % name)
def __setattr__(self, name, value):
self[name] = value
def __delattr__(self, name):
if name in self:
del self[name]
else:
raise AttributeError('No such attribute: %s' % name)
有人可以为我解释这段代码吗?我只是一个蟒蛇初学者。
答案 0 :(得分:2)
ObjectDict实例是通过类继承的常规字典。见ObjectDict(dict)
__getattr__
魔术函数允许定义任何对象的点符号访问。它只是在这里调用普通字典访问
同样,__setattr__
和__delattr__
允许使用点符号设置和删除(使用Python的del
表达式)值。但是,要设置嵌套值,您需要第一个键的值也是ObjectDict
答案 1 :(得分:0)
__getattr__
适用于获取数据的时间。
__setattr__
适用于设置数据的时间。
__delattr__
适用于 del 数据的时间。
现在,方法应该很清楚。
def __getattr__(self, name):
# if the key exists... return it.
if name in self:
return self[name]
# if not : raise an error.
else:
raise AttributeError('No such attribute: %s' % name)
def __setattr__(self, name, value):
# set VALUE as value, with NAME as key in the dict.
self[name] = value
def __delattr__(self, name):
# if the key "name" exists in the dictionnary... delete it
if name in self:
del self[name]
# else, it doesnt exist, so cant delete it.
else:
raise AttributeError('No such attribute: %s' % name)