在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)
答案 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
实例名称的内容是不明确的。