python - 如何在 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'
解决方案
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)
推荐阅读
- python - 在 colab 中跨细胞坚持 conda env
- c++ - 为什么不能读取文件(不显示数据)?
- python - 有没有办法在 PyTorch DataParallel 中处理与 batch_index 相关的数据
- python - 如何只打印 JSON 对象的一部分数据?
- c - osDelay() 等待时间不够
- google-apps-script - 带有 Bearer 令牌的 Google App 脚本 UrlFetchApp 但收到错误请求
- python - 如何根据具有外键关系的另一个模型更新 Django 模型的字段
- nlp - 为什么 Amazon Comprehend Medical 在一个文本简介中识别出药物实体,而在另一个文本简介中识别不出来?
- git - 如何 gitignore firebase 缓存?
- python - 在 Python 中使用随机模块获取唯一数字