From 2ac5acc591c88243c5679a93182a797f66c5d93d Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Thu, 6 Aug 2009 17:29:07 -0700 Subject: [PATCH] clarify self.keys() --- special-method-names.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/special-method-names.html b/special-method-names.html index 3da0b56..da77766 100644 --- a/special-method-names.html +++ b/special-method-names.html @@ -289,12 +289,13 @@ class FieldStorage: return any(item.name == key for item in self.list) def __len__(self): - return len(self.keys()) + return len(self.keys())
  1. Once you create an instance of the cgi.FieldStorage class, you can use the “in” operator to check whether a particular parameter was included in the query string.
  2. The __contains__() method is the magic that makes this work.
  3. When you say if 'q' in fs, Python looks for the __contains__() method on the fs object, which is defined in cgi.py. The value 'q' is passed into the __contains__() method as the key argument.
  4. The same FieldStorage class also supports returning its length, so you can say len(fs) and it will call the __len__() method on the FieldStorage class to return the number of query parameters that it identified. +
  5. The self.keys() method checks whether self.list is None, so the __len__ method doesn’t need to duplicate this error checking.

Classes That Act Like Dictionaries