Python - Access a class from a list using a key
Posted
by Fake Name
on Stack Overflow
See other posts from Stack Overflow
or by Fake Name
Published on 2010-04-05T08:42:24Z
Indexed on
2010/04/05
8:43 UTC
Read the original article
Hit count: 175
Is there any way to make a list of classes behave like a set in python?
Basically, I'm working on a piece of software that does some involved string comparison, and I have a custom class for handling the strings. Therefore, there is an instance of the class for each string.
As a result, I have a large list containing all these classes. I would like to be able to access them like list[key]
, where in this case, the key is a string the class is based off of.
It seems to me that I sould be able to do this somewhat easily, by adding something like __cmp__
to the class, but either I'm being obtuse (likely), or Im missing someting in the docs.
Basically, I want to be able to do something like this (Python prompt example):
>>class a:
... def __init__(self, x):
... self.var = x
...
>>> from test import a
>>> cl = set([a("Hello"), a("World"), a("Pie")])
>>> print cl
set([<test.a instance at 0x00C866C0>, <test.a instance at 0x00C866E8>, <test.a instance at 0x00C86710>])
>>> cl["World"]
<test.a instance at 0x00C866E8>
Thanks!
© Stack Overflow or respective owner