Class subscripting

skip at pobox.com skip at pobox.com
Fri Feb 17 19:56:32 EST 2006


    Ronny> Assume we have a class Foo, and instance called bar.  a variable
    Ronny> called baz1 has the value 3.0, baz2 is uninitialized

    Ronny> Is there a way of reflecting the variable with such syntax:

    Ronny> print bar[<var_index>], where var_index is a number representing
    Ronny> internal index.

    Ronny> bar[<var_index>] = 4.2. #Setting baz2 to 4.2

Sure.  Check out the special method names for container types:

    http://www.python.org/dev/doc/devel/ref/sequence-types.html

To index into instances of your class you need to define a __getitem__
method.

Skip




More information about the Python-list mailing list