Why aren't colons optional?
Huaiyu Zhu
huaiyu at gauss.almadan.ibm.com
Mon Jan 21 16:58:57 EST 2002
On Sun, 20 Jan 2002 16:39:52 -0500, Roy Smith <roy at panix.com> wrote:
>Alex Martelli <aleax at aleax.it> wrote:
>
>> No, it would have substantially impoverished the language:
>>
>> class doubleface:
>> def __getitem__(self, name):
>> return "anitem"
>> def __call__(self, *args):
>> return "acall"
>
>Can you give me a practical example of why somebody would want to define a
>__getitem__ method for a class?
The UserDict class has __getitem__, as it simulates a dictionary. I guess
you wanted to ask about __call__. Here's one example:
from UserDict import UserDict
class Dispatcher(UserDict):
def __call__(self, cmd_name, *args):
actual_cmd = self[cmd_name]
return actual_cmd(*args)
import operator
d = Dispatcher(operator.__dict__)
print d("add", 2, 3)
Huaiyu
More information about the Python-list
mailing list