Quantcast
Channel: Best practice for using assert? - Stack Overflow
Viewing all articles
Browse latest Browse all 17

Answer by Nadia Alramli for Best practice for using assert?

$
0
0

To be able to automatically throw an error when x become less than zero throughout the function. You can use class descriptors. Here is an example:

class LessThanZeroException(Exception):    passclass variable(object):    def __init__(self, value=0):        self.__x = value    def __set__(self, obj, value):        if value < 0:            raise LessThanZeroException('x is less than zero')        self.__x  = value    def __get__(self, obj, objType):        return self.__xclass MyClass(object):    x = variable()>>> m = MyClass()>>> m.x = 10>>> m.x -= 20Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "my.py", line 7, in __set__    raise LessThanZeroException('x is less than zero')LessThanZeroException: x is less than zero

Viewing all articles
Browse latest Browse all 17

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>