Python Get Variable Name Inside Class
<p>In Python 3, if you have a class, like this:</p>

<pre><code>LETTERS = list('abcdefghijklmnopqrstuvwxyz')
class letter:
    def __init__(self, name):
        self.number = LETTERS.index(name)
        self.nextLetter = LETTERS[self.number+1]
        self.previousLetter = LETTERS[self.number-1]
</code></pre>

<p>and you create an instance of letter, myLetter, like this:</p>

<p><code>myLetter = letter('c')</code></p>

<p>In letter, how do I get the variable name? (myLetter in this case)</p>

<p>Think of <code>myLetter</code> as a pointer to the class instance of <code>letter</code>. For example, if you have:</p>

<pre><code>LETTERS = list('abcdefghijklmnopqrstuvwxyz')
class letter:
    def __init__(self, name):
        self.number = LETTERS.index(name)
        self.nextLetter = LETTERS[self.number+1]
        self.previousLetter = LETTERS[self.number-1]

myLetter = letter('c')
myLetter2 = myLetter
</code></pre>

<p>Both myLetter and myLetter2 are aliases for the exact same myLetter instance. For example:</p>

<pre><code>myLetter.number = 50
print(myLetter2.number)

&gt;&gt;&gt; 50
</code></pre>

<p>So finding something to return the name of the <code>letter</code> instance within the <code>letter</code> class is ambiguous.</p>

python class python-3.x