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)
asked Oct 8, 2016 at 17:31
nedla2004
1,1453 gold badges14 silver badges29 bronze badges
1 Answer 1
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.
answered Oct 8, 2016 at 18:22
Brian
1,9981 gold badge17 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
letter(you should capitalize your class names ->class Letter) calledmyLetterand now are asking how to getmyLetterfromletter?letter, I am trying to getmyLetter.list_of_letters = [letter('a'), letter('b')]ora = b = letter('c'). Which variable name would you expect in those cases? What you're asking for is generally not possible (though you might be able to get what you want by inspecting the stack), and shouldn't be used even if it was possible. Variable names are not data. If you want a mapping from a "name" string to an instance, use a dictionary.