我试图找到一种方法来设置封装在类中的字典值,例如使用__getattr__可以返回内部字典值,但是__setattr__即使存在属性也会被调用,使我的实现变得丑陋。下面的示例简化了我的实际类,它继承自Subject类(观察者模式中的subject部分)。
我试图实现以下内容:
我想知道是否有比我下面所做的更好的方法:
我试图实现以下内容:
obj = Example()
obj.username = 'spidername' # all OK username is a key in the internal dict
# but company is not a key in the internal dict so
obj.company = 'ABC' # will raise AttributeError
我想知道是否有比我下面所做的更好的方法:
class Example(object):
def __init__(self, table=None):
self._fields = {}
self._table = table
def _set_fields(self):
"""
this method will be implemented by
subclasses and used to set fields names and values
i.e.
self._field['username'] = Field(default='unknown', is_primary=False)
"""
raise NotImplementedError
def __getattr__(self, name):
"""
great this method is only called when "name"
is not an attribute of this class
"""
if name in self._fields:
return self._fields[name].value
return None
def __setattr__(self, name, value):
"""
not so great, this method is called even for
attributes that exists in this class
is there a better way to do the following?
this can be in __init__, but its still ugly
"""
attribs = ['_fields', '_table']
if name in attribs:
super(Example, self).__setattr__(name, value)
else:
if name in self._fields:
self._fields[name].value = value
else:
raise AttributeError
编辑:修改代码中的注释,添加缺失的引号。