nedla2004 nedla2004 - 1 month ago 10
Python Question

Python Get Variable Name Inside Class

In Python 3, if you have a class, like this:

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]


and you create an instance of letter, myLetter, like this:

myLetter = letter('c')


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

Answer

Think of myLetter as a pointer to the class instance of letter. For example, if you have:

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

Both myLetter and myLetter2 are aliases for the exact same myLetter instance. For example:

myLetter.number = 50
print(myLetter2.number)

>>> 50

So finding something to return the name of the letter instance within the letter class is ambiguous.