[Python-Dev] Re: Sets: elt in dict, lst.include

Tim Peters tim.one@home.com
2001年1月31日 15:56:52 -0500


[Ping]
> x is sequence-like if it provides __getitem__() but not keys()

[Skip]
> So why does this barf?
>> >>> [].__getitem__
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> AttributeError: __getitem__
>> (Obviously, lists *do* understand __getitem__ at some level. Why
> isn't it exposed in the method table?)

The old type/class split: list is a type, and types spell their "method
tables" in ways that have little in common with how classes do it.
See PyObject_GetItem in abstract.c for gory details (e.g., dicts spell their
version of getitem via ->tp_as_mapping->mp_subscript(...), while lists spell
it ->tp_as_sequence->sq_item(...); neither has any binding to the attr
"__getitem__"; instance objects fill in both the tp_as_mapping and
tp_as_sequence slots, then map both the mp_subscript and sq_item slots to
classobject.c's instance_item, which in turn looks up "__getitem__").
bet-you're-sorry-you-asked<wink>-ly y'rs - tim

AltStyle によって変換されたページ (->オリジナル) /