hasattrr 检查 python 中对象的属性

hasattrr to check properties of a object in python

我正在使用 Python flask 编写 Web 服务。我创建了一个 class 并从用户输入中加载其 属性 名称和值(json 服务调用提供的数据)。

from flask import json
class DataSetContract(object):
    """description of class"""

    def __init__(self, j):
        self.__dict__ = json.loads(j)

我还得到了一个值 属性 名称的列表,作为我服务的其他输入的一部分。

无法实现... 例如属性列表... {"from value","To Value","some values"}

属性 名称中有空格。

我有另一个 class 用于保存这些 属性 名称

class FxConvertContract(object):
    """description of class"""

    def __init__(self, j):
        self.INPUT_CURRENCY = ""
        self.INPUT_AMOUNT = "" 
        self.RETURN_CURRENCY = ""
        self.RETURN_VALUE = ""
        self.ROUNDING = ""
        self.RETURN_RATE = ""
        self.__dict__ = json.loads(j)

现在的目标是如何验证列表中的所有属性是否已正确填充并且 none 是否缺失。

我尝试了 'in' 和 'hasattr' 方法,但没有任何效果。

class DataSetValidator(object):

    def validate(self,dsList,convert):
        if(dsList == None or len(dsList) < 1):
            raise BadRequest("either Convert List or Data Set Source required.")

        for item in dsList:
            if(convert.INPUT_CURRENCY in item):
                raise BadRequest("INPUT_CURRENCY property not found.")
            if(hasattr(item,convert.INPUT_AMOUNT) == False):
                raise BadRequest("INPUT_AMOUNT property not found.")
            if(hasattr(item,convert.RETURN_CURRENCY) == False):
                raise BadRequest("RETURN_CURRENCY property not found.")
            if(hasattr(item,convert.RETURN_VALUE) == False):
                raise BadRequest("RETURN_VALUE property not found.")

        return True

有谁知道如何验证数据对象是否包含所有属性。

提前致谢...

假设这就是您要执行的操作,hasattr 将起作用:

In [1]: from flask import json 
   ...: class DataSetContract(object): 
   ...:     """description of class""" 
   ...:  
   ...:     def __init__(self, j): 
   ...:         self.__dict__ = json.loads(j) 
   ...:                                                                                                                                                                 

In [2]: class FxConvertContract(object): 
   ...:     """description of class""" 
   ...:  
   ...:     def __init__(self, j): 
   ...:         self.INPUT_CURRENCY = "" 
   ...:         self.INPUT_AMOUNT = ""  
   ...:         self.RETURN_CURRENCY = "" 
   ...:         self.RETURN_VALUE = "" 
   ...:         self.ROUNDING = "" 
   ...:         self.RETURN_RATE = "" 
   ...:         self.__dict__ = json.loads(j) 
   ...:                                                                                                                                                                 

In [3]: class DataSetValidator(object): 
   ...:  
   ...:     def validate(self, dsList, convert): 
   ...:         if(dsList is None or len(dsList) < 1): 
   ...:             raise BadRequest("either Convert List or Data Set Source required.") 
   ...:  
   ...:         for item in dsList: 
   ...:             if(not hasattr(item, convert.INPUT_CURRENCY)): 
   ...:                 raise BadRequest("INPUT_CURRENCY property not found.") 
   ...:             if(not hasattr(item, convert.INPUT_AMOUNT)): 
   ...:                 raise BadRequest("INPUT_AMOUNT property not found.") 
   ...:             if(not hasattr(item, convert.RETURN_CURRENCY)): 
   ...:                 raise BadRequest("RETURN_CURRENCY property not found.") 
   ...:             if(not hasattr(item, convert.RETURN_VALUE)): 
   ...:                 raise BadRequest("RETURN_VALUE property not found.") 
   ...:  
   ...:         return True 
   ...:                                                                                                                                                                 

In [4]: class BadRequest(Exception): pass                                                                                                                               

In [7]: contract = FxConvertContract("""{ 
   ...:     "INPUT_CURRENCY": "in_currency", 
   ...:     "INPUT_AMOUNT": "in_amount", 
   ...:     "RETURN_CURRENCY": "re_currency", 
   ...:     "RETURN_VALUE": "re_value", 
   ...:     "ROUNDING": "rounding", 
   ...:     "RETURN_RATE": "re_rate" 
   ...: }""")                                                                                                                                                           

In [8]: data = DataSetContract("""{ 
   ...:     "in_currency": "USD", 
   ...:     "in_amount": 1, 
   ...:     "re_currency": "CAD", 
   ...:     "re_value": 1.33, 
   ...:     "rounding": 0, 
   ...:     "re_rate": 1.33 
   ...: }""")                                                                                                                                                           

In [9]: validator = DataSetValidator()                                                                                                                                  

In [12]: validator.validate([data], contract)                                                                                                                            
Out[12]: True

你可以像这样做一些聪明而愚蠢的事情

fields = [
    'INPUT_CURRENCY', 
    'INPUT_AMOUNT', 
    'RETURN_CURRENCY', 
    'RETURN_VALUE', 
    'ROUNDING', 
    'RETURN_RATE'
]
data = json.loads(j)
test = [f in data for f in fields]  # a list of booleans
if not all(test):
    idx = test.index(False)
    raise BadRequest("%s property not found." % fields[idx])