鉴于以下设置,我需要尝试创建一个MyClass
实例并记录每个异常@property setter抛出(而不仅仅是第一个)。
class MyClassFactory(object):
def __init__(self, data):
d = {
"age": sanitize(data, 'age'),
"name": sanitize(data, 'name')
}
for (k, v) in d.items():
setattr(self, k, v)
mc = MyClass()
for prop in self.__dict__.items():
try:
# assign value to MyClass instance
except MyException as e:
raise
class MyClass(object):
def __init__(self):
self._age = None
self._name = None
@property
def age(self):
return self._age
@age.setter
def age(self, age):
if age != '':
try:
self._age = int(age)
except ValueError:
raise MyException
else:
raise MyException
# similar property for `name`
# ...
if __name__ == '__main__':
data = loadjson()
for record in data:
f = MyClassFactory(record)
我可以像下面这样做,但是我有更多的属性。我如何
MyClass
和MyClassFactory
个属性
try:
mc.age = self.age
except MyException as e:
raise
try:
mc.name = self.name
except MyException as e:
raise
# ... many more
答案 0 :(得分:1)
MyClass类可以捕获setter方法中的所有异常,并将它们存储在' _exceptions' list / dict变量属于MyClass。
您的工厂类可以验证此列表/字典是否为空。如果没有,您可以访问这一个地方的所有例外情况。