Class subscripting

Ian Leitch port001 at gentoo.org
Fri Feb 17 19:32:00 EST 2006


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Ronny Mandal wrote:
> Assume we have a class Foo, and instance called bar.
> 
> a variable called baz1 has the value 3.0, baz2 is uninitialized
> 
> Is there a way of reflecting the variable with such syntax:
> 
> print bar[<var_index>], where var_index is a number representing
> internal index.
> 
> bar[<var_index>] = 4.2. #Setting baz2 to 4.2

Hmmm... I don't like this much, though it'd could be a little better if
you kept a separate list which you update in __setitem__ instead of
constructing a new list for each __getitem__ call.

I'm sure someone has a more elegant solution, I'm afraid I'm too tired
to come up with anything better.

Oh, and don't forget to check that key is an IntType!

class MyClass:

    def __init__(self):

        self.a = "I'm a!"
        self.b = "I'm b!"

    def __getitem__(self, key):

        if key != None:

            return list(self.__dict__.values())[key]

x = MyClass()
print x[0]
print x[1]


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFD9msAefZ4eWAXRGIRAjN0AJ40pfI5fhm2WK7gV1Q4dEr9Nv10TgCgo6mY
ovWBqjXvdSjH3zNh61j5qj4=
=XrYe
-----END PGP SIGNATURE-----



More information about the Python-list mailing list