【发布时间】:2020-08-06 06:59:23
【问题描述】:
我希望能够在类属性上使用方法(例如 .upper() 或 .lower())。 例如,在下面的代码中:
class Player:
def __init__(self, score,):
self.score = score
self.username = str(self)
self.password = str((self.upper()))
player1 = Player(0)
print(player1.password)
我希望打印语句打印出“PLAYER1”,但我却收到了
AttributeError: 'Player' object has no attribute 'upper'
【问题讨论】:
-
str(self)不会返回变量名(即player1)。你不能像那样访问变量名。 -
要点是对象可以有任意多个名称(即0到很多),因此既不知道也不知道“他们的名字”。如果你想使用一个对象,你必须告诉它的名字。
标签: python python-3.x class methods attributes