我似乎无法弄清楚如何获取类数据描述符的列表。基本上,我想对字段和未设置的字段进行一些验证。例如:
class Field (object):
def __init__ (self, name, required=False):
self.name = name
self.required = required
def __set__ (self, obj, val):
obj.__dict__[self.name] = val
def __get__ (self, obj):
if obj == None:
raise AttributeError
if self.name not in obj.__dict__:
raise AttributeError
return obj.__dict__[self.name]
然后我想在这样的模型中实现它:
class BaseModel (object):
some_attr = Field('some_attr', required=True)
def save (self):
for field in fields:
if field.required and field.name not in self.__dict__:
raise Exeception, 'Validation Error'
我将如何获取我定义的字段列表?我在想,我可以做到以下几点:
import inspect
fields = []
for attr in self.__class__.__dict__:
if inspect.isdatadescriptor(self.__class__.__dict__[attr]):
fields.append(attr)
但是我遇到了继承问题,有什么想法吗?