Python在类中获取变量名称

时间:2016-10-08 17:31:01

标签: python class python-3.x

在Python 3中,如果你有一个类,如下所示:

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的实例,如下所示:

myLetter = letter('c')

在信中,我如何获得变量名称? (在这种情况下是myLetter)

1 个答案:

答案 0 :(得分:2)

myLetter视为指向letter的类实例的指针。例如,如果您有:

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

myLetter和myLetter2都是完全相同的myLetter实例的别名。例如:

myLetter.number = 50
print(myLetter2.number)

>>> 50

因此,在letter类中查找返回letter实例名称的内容是不明确的。