首页 > 解决方案 > 如何在 Python3 中的类属性上使用方法?

问题描述

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

标签: pythonpython-3.xclassmethodsattributes

解决方案


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

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

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

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

您收到错误消息:

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

因为当你说 self.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)

推荐阅读