[Tutor] Question about 'Predicate Methods'
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Mon Mar 24 13:24:01 2003
On Mon, 24 Mar 2003, ahimsa wrote:
> In Deitel, et al. ("Python: how to program", 2002:233), the concept of
> 'predicate' methods is introduced with reference to access control
> methods protecting object's attributes from being 'gotten' at and
> rendered inconsistent by client code. It is described as a 'read-only'
> access method that test the validity of a condition.
A "predicate" is a function that either returns a true or false value,
depending on what it's trying to test. Here are some examples of
predicates:
###
>>> def is_even(x):
... return x % 2 == 0
...
>>> def is_odd(x):
... return not is_even(x)
...
>>> is_even(42)
1
>>> is_odd(42)
0
>>> def is_happy(word):
... return word in ('happy', 'blissful', 'bright', 'elysian',
... 'golden', 'halycyon', 'joyful', 'laughing')
...
>>> is_happy('me')
0
>>> is_happy('blissful')
1
###
(In the newest versions of Python, the results of the above tests will
return the values 'True' and 'False', rather than 1 and 0, so expect to
see slightly different displays.)
In that sense, a predicate is simply a function that tells us if something
is true or not. A predicate method, then, is a method that gives us that
true or false value.
We often bundle these condition tests into predicates when we want to make
the code clearer: we want to often give a concrete name to something that
fulfills certain requirements. For example, we might say that a word is
"palindromic" if it's spelled forwards and backwards the same:
###
# pseudocode, since we haven't really defined is_palindrome() yet...
>>> is_palindrome('aba')
1
>>> is_palindrome('rotator')
1
>>> is_palindrome('palindrome')
0
###
So the concept of a predicate --- a boolean function --- isn't really that
profound. *grin*
Hope this helps!