如何在 Python3 中的 class 属性上使用方法?

How do I use a method on a class attribute in Python3?

我希望能够在 class 属性上使用方法(例如 .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'

Self 是一个变量名,表示 class 的一个实例。它是引用class的当前对象的参数。通过使用它我们可以访问class.

的参数和方法

您需要使用 self 的原因是因为 Python 不使用 @ 语法来引用实例属性。

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

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

您遇到错误:

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

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

在下面的代码中:

self 是一个对象来指定class 方法的实例。并且 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)

你可以在class中添加属性,这样当用户输入他们的用户名和密码时。它是一个字符串。然后就可以使用.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

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