我有使用@property装饰器设置属性的类.它们使用try和except子句作为getter和setter.如果未设置attribute,它将从数据库获取数据并使用它来从其他类中实例化对象.我试图保持示例简短,但用于实例化属性对象的代码与每个属性略有不同.他们的共同点是尝试 - 开头时除外.
class SubClass(TopClass):
@property
def thing(self):
try:
return self._thing
except AttributeError:
# We don't have any thing yet
pass
thing = get_some_thing_from_db('thing')
if not thing:
raise AttributeError()
self._thing = TheThing(thing)
return self._thing
@property
def another_thing(self):
try:
return self._another_thing
except AttributeError:
# We don't have things like this yet
pass
another_thing = get_some_thing_from_db('another')
if not another_thing:
raise AttributeError()
self._another_thing = AnotherThing(another_thing)
return self._another_thing
...etc...
@property
def one_more_thing(self):
try:
return self._one_more_thing
except AttributeError:
# We don't have this …Run Code Online (Sandbox Code Playgroud)