【问题标题】:How do I use a method on a class attribute in Python3?如何在 Python3 中对类属性使用方法?
【发布时间】: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


【解决方案1】:

Self 是一个变量名,代表类的一个实例。它是引用类的当前对象的参数。通过使用它我们可以访问类的参数和方法。

之所以需要使用self是因为Python不使用@语法来引用实例属性。

注意:您可以为该变量命名任何名称。但它必须是第一个参数。例如:

class Player:
    def__init__(myclassobj, score):
        myclassobj.score = score
        myclassobj.username ...
        ...
        ...

你得到了错误:

AttributeError: 'Player' object has no attribute 'upper'

因为当你说self.upper时,它会在类实例中搜索一个属性,而你还没有定义任何upper属性。

在下面的代码中:

self 是一个对象来指定类的实例的方法。并且 score 不能与 .upper 一起使用,因为它是整数类型。

class Player:
    def __init__(self, score,):
        self.score = score
        self.username = str(score)
        self.password = str((score.upper()))
        
player1 = Player(0)
print(player1.password)

根据我的理解应该是:

class Player:
    def __init__(self, score, username, password):
        self.score = score
        self.username = str(username)
        self.password = str((password.upper()))
        
player1 = Player(0, 'ABC', 'abc@123')
print(player1.password)

【讨论】:

  • 请澄清。 self一个变量名。 score.upper() 既不能工作 (AttributeError: 'int' object has no attribute 'upper') 也不能远程产生所需的结果 (PLAYER1)。
【解决方案2】:

您可以在类中添加属性,以便在用户输入用户名和密码时。它是一个字符串。然后就可以使用 .upper() 方法了。

class Player:
    def __init__(self, username, password, score,):
        self.score = score
        self.username = username.upper()
        self.password = password.upper()
        
player1 = Player("tom", "abcd1234",0)

print(player1.username)
print(player1.password)

输出:

TOM
ABCD1234

【讨论】:

    【解决方案3】:

    那是因为你调用的是对象本身,而不是对象名 upper() 是字符串的方法,所以它不会在 self 上

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      相关资源
      最近更新 更多