Monday, 25 November 2013

property()

Last week we learned about the built-in python function property. I didn't really know how to use this function until I asked for advice on Piazza. But even after figuring out I wasn't really sure what the point of this function was because up until now we've been assigning values as self.x = x as soon as we called our class. But I soon realized that you can add if statements to prevent future users of your code to input invalid values. The example Danny used was:

    symbol = property(get_symbol, set_symbol, None, None)

    def set_symbol(self: 'RegexTreeNode', s: str) -> None:
        """set private symbol"""
        if not s in '01e|.*':
            raise Exception('Invalid symbol: {}'.format(s))
        else:
            self._symbol = s

The highlighted part in set_symbol made it so that if the someone was to pass a value other than 01e|.* as the parameter then an error would be raised. This could be one of the pitfalls in A2, even though it was not specified that we had to take such cases into consideration.

After reading the slogs of my classmates, it seems like others are also having trouble understanding how to use the property function and what it should be used for.

I look forward to using this function in my future code.

No comments:

Post a Comment