Python Get Variable Name Inside Class

2019-03-05 13:13发布

问题:

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)

回答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.