Note that there are some explanatory texts on larger screens.

plurals
  1. POPython - Access a class from a list using a key
    text
    copied!<p>Is there any way to make a list of classes behave like a set in python?</p> <p>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.</p> <p>As a result, I have a large list containing all these classes. I would like to be able to access them like <code>list[key]</code>, where in this case, the key is a string the class is based off of (note: the string will never change once the class is instantiated, so it should be hashable).</p> <p>It seems to me that I should be able to do this somewhat easily, by adding something like <code>__cmp__</code> to the class, but either I'm being obtuse (likely), or I'm missing something in the docs.</p> <p>Basically, I want to be able to do something like this (Python prompt example):</p> <pre><code>&gt;&gt;class a: ... def __init__(self, x): ... self.var = x ... &gt;&gt;&gt; from test import a &gt;&gt;&gt; cl = set([a("Hello"), a("World"), a("Pie")]) &gt;&gt;&gt; print cl set([&lt;test.a instance at 0x00C866C0&gt;, &lt;test.a instance at 0x00C866E8&gt;, &lt;test.a instance at 0x00C86710&gt;]) &gt;&gt;&gt; cl["World"] &lt;test.a instance at 0x00C866E8&gt; </code></pre> <p>Thanks!</p> <p><em>Edit</em> Some additional Tweaks:</p> <pre><code>class a: ... def __init__(self, x): ... self.var = x ... def __hash__(self): ... return hash(self.var) ... &gt;&gt;&gt; v = a("Hello") &gt;&gt;&gt; x = {} &gt;&gt;&gt; x[v]=v &gt;&gt;&gt; x["Hello"] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'Hello' &gt;&gt;&gt; x["Hello"] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload