0

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)

13
  • I'm not following. You created an instance of letter (you should capitalize your class names -> class Letter) called myLetter and now are asking how to get myLetter from letter? Commented Oct 8, 2016 at 17:32
  • Inside letter, I am trying to get myLetter. Commented Oct 8, 2016 at 17:35
  • 1
    Could you explain why you need this? Otherwise this seems like an XY Problem Commented Oct 8, 2016 at 17:44
  • 2
    An instance doesn't always have a variable name (or only one, for that matter). Consider list_of_letters = [letter('a'), letter('b')] or a = 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. Commented Oct 8, 2016 at 18:16
  • 1
    This is nearly impossibel. See stackoverflow.com/a/18425275/4273834 Commented Oct 8, 2016 at 18:16

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.