首页 > 解决方案 > 如何在类中使用字典中的项目?

问题描述

我希望在打印时使用角色的性别代词,例如:

“国王卫队”拔出了“他的”剑。

“他的”是重要的部分。

我收到此错误: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'])

标签: pythonclassoopdictionary

解决方案


您的逻辑使问题过于复杂。您可以直接访问类实例的方法:

print(kingsguard.pronoun()['them'])  # 'he'

a_noun = Player.pronoun()将无法按预期工作,因为该类需要知道哪个实例pronoun属于。否则将无法访问self.gender


推荐阅读