如何从一个类中使用Dictionary中的项目?

时间:2018-09-30 10:59:16

标签: python class oop dictionary

我希望在打印时使用一个字符的性别使用代词,例如:

“国王卫队”拉“他的”剑。

“他的”是重要的部分。

我收到此错误: TypeError:pronoun()缺少1个必需的位置参数:“ 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'])

1 个答案:

答案 0 :(得分:0)

您的逻辑使问题变得更加复杂。您可以直接访问实例类的方法:

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

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