In week 11 of csc148, two powerful functions of python are introduced in lectures, which are property() and reduce().
Function property() takes 4 parameters(fget, fset, fdel, doc). fget, fset, fdel are three methods in a class, they are used to return the value, set the value, del the value. We can add some restrictions to these methods.
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
then, if we add symbol = property(get_symbol, set_symbol, None, None) in the class
>>> a = RegexTreeNode('1',[])
>>> a.symbol = 'a'
it will raise exception
Another functionality of this function is to prevent the value from being set or deleted by users.(i.e. read-only). If we add symbol = property(get_symbol, None, None, None) in the class, we can no longer set the value of object.symbol.
Above all, by indicating a = property() can create a new attribute "a" of the class, and we can set some restrictions on the getting, setting, deleting of that attribute.
The second powerful function is reduce(). It takes three arguments(function, iterable, initializer). For example, reduce(lambda x, y: x + y, [1,2,3,4,5], 0) calculates 1+2+3+4+5 = 15. The first argument must be a function which takes two arguments. The third argument is the initial value, without which there will be an error if the list is empty list. The reduce() function makes it simple to apply a function on an iterable object over and over again and finally get reduce the iterable object into one value.
没有评论:
发表评论