Correct approach to validate attributes of an instance of class

前端 未结 5 1747
无人及你
无人及你 2020-12-04 06:17

Having a simple Python class like this:

class Spam(object):
    __init__(self, description, value):
        self.description = description
        self.value         


        
5条回答
  •  天命终不由人
    2020-12-04 06:52

    You can use Python properties to cleanly apply rules to each field separately, and enforce them even when client code tries to change the field:

    class Spam(object):
        def __init__(self, description, value):
            self.description = description
            self.value = value
    
        @property
        def description(self):
            return self._description
    
        @description.setter
        def description(self, d):
            if not d: raise Exception("description cannot be empty")
            self._description = d
    
        @property
        def value(self):
            return self._value
    
        @value.setter
        def value(self, v):
            if not (v > 0): raise Exception("value must be greater than zero")
            self._value = v
    

    An exception will be thrown on any attempt to violate the rules, even in the __init__ function, in which case object construction will fail.

    UPDATE: Sometime between 2010 and now, I learned about operator.attrgetter:

    import operator
    
    class Spam(object):
        def __init__(self, description, value):
            self.description = description
            self.value = value
    
        description = property(operator.attrgetter('_description'))
    
        @description.setter
        def description(self, d):
            if not d: raise Exception("description cannot be empty")
            self._description = d
    
        value = property(operator.attrgetter('_value'))
    
        @value.setter
        def value(self, v):
            if not (v > 0): raise Exception("value must be greater than zero")
            self._value = v
    

提交回复
热议问题