Trying to understand Python objects

George Sakkis george.sakkis at gmail.com
Thu Nov 23 21:21:52 CET 2006


Bruno Desthuilliers wrote:

> AFAIK, everything you do with old-style classes can be done with new-style ones.

The only thing I occasionally (or rather rarely) miss about old-style
classes is instance-specific special methods:

>>> class C:
...     def __init__(self,x):
...         self.__getitem__ = lambda i: i*x
...
>>> c=C(2)
>>> c[3]
6
>>> class N(object):
...     def __init__(self,x):
...         self.__getitem__ = lambda i: i*x
...
>>> n=N(2)
>>> n[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unindexable object

Of course this example can be rewritten to work for new style classes;
a trickier would be to bind the instance attribute conditionally;
here's a silly example:

>>> class C:
...     def __init__(self,x):
...         if random.random() > 0.5:
...             self.__getitem__ = lambda i: i*x

I'm not sure if this is a conscious choice or a technical limitation of
how new-style classes work internally, but I've had a use for it at
least once.

George




More information about the Python-list mailing list