python - 如何在类中使用字典中的项目?
问题描述
我希望在打印时使用角色的性别代词,例如:
“国王卫队”拔出了“他的”剑。
“他的”是重要的部分。
我收到此错误:TypeError: pronoun() missing 1 required positional argument: 'self'
class Player(object):
# instantiates each character with a range of functions
def __init__(self, name, health, lives, gender, inventory):
self.name = name
self.health = int(health)
self.lives = int(lives)
self.gender = gender
self.inventory = []
def pronoun(self):
if 'male' in self.gender:
nouns = {
'them': 'he',
'their': 'his'
}
if 'female' in self.gender:
nouns = {
'them': 'she',
'their': 'her'
}
return nouns
player = Player("Kate", 100, 3, 'female', 'Axe')
kingsguard = Player("The Kings Guard", 150, 1, 'male', None)
a_noun = Player.pronoun()
print(kingsguard.a_noun['them'])
解决方案
您的逻辑使问题过于复杂。您可以直接访问类实例的方法:
print(kingsguard.pronoun()['them']) # 'he'
a_noun = Player.pronoun()
将无法按预期工作,因为该类需要知道哪个实例pronoun
属于。否则将无法访问self.gender
。
推荐阅读
- java - 如何使用 Java regexp 从文本中排除双重配额?
- java - 如何在 apache poi 3.17 中调用 trackAllColumnsForAutoSizing() 方法
- jquery - Laravel 5.2 编辑按钮单击时不显示模态内容
- java - 从 Rest 客户端请求通过服务到 Web 应用程序检索 JSON
- hyperledger-fabric - Hypereldger Fabric 中的应用能力 v1.2
- git - 回到上一个 github 提交
- media-queries - 使用媒体查询隐藏元素
- mysql - 最大日期,在 2 个表 MYSQL 中找到每个用户的余额
- python - Flask 启动新线程 - RuntimeError:在请求上下文之外工作
- php - Laravel firstOrCreate 搜索关系