Wednesday, 20 November 2013

Identity, Information hiding, Reduce

1.Hiding attributes:

class C: def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.")

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget‘s docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:

Make something 'READ-ONLY':
example:
def get_children(self: 'RegexTreeNode') -> list:
"""get private children"""
return self._children
children = property(get_children, None, None, None)

2.Equality:

Want two things that point to the the same content to be equivalent!

For RegexTreeNode:
we want to check whether they have the same symbols and the same children:
def __eq__(self: 'RegexTreeNode', other: 'RegexTreeNode') -> bool:
"""is this RTN equivalent to other?"""
return (self.symbol == other.symbol and
all([c1.__eq__(c2)
for c1, c2 in zip(self.children,other.children)]))


3.Reduce:

Reduce  allows you to combine the elements of an iterable into a single, somehow reduced value.


Example: suppose you want to multiply all the numbers in a list:
from functools import reduce
reduce(int.__mul__, [1,2,3,4,5])

wiki-link for MapReduce: http://en.wikipedia.org/wiki/MapReduce

No comments:

Post a Comment