首页 > 解决方案 > 父类对手方法将由子类继承。完整的问题细节在评论中

问题描述

在父类中编写另一个将被子类继承的方法。称之为对手。它应该返回哪种类型的口袋妖怪当前类型是弱和强的,作为元组。草对火弱,对水强 鬼对暗弱,对心灵强 火对水弱,对草强, .opponent() 应该返回元组 ('Fire', 'Water')

class Pokemon():
    attack = 12
    defense = 10
    health = 15
    p_type = "Normal"

    def __init__(self, name,level = 5):
        self.name = name
        self.level = level
        self.weak = "Normal"
        self.strong = "Normal"

    def train(self):
        self.update()
        self.attack_up()
        self.defense_up()
        self.health_up()
        self.level = self.level + 1
        if self.level%self.evolve == 0:
            return self.level, "Evolved!"
        else:
            return self.level

    def attack_up(self):
        self.attack = self.attack + self.attack_boost
        return self.attack
    def defense_up(self):
        self.defense = self.defense + self.defense_boost
        return self.defense

    def health_up(self):
        self.health = self.health + self.health_boost
        return self.health

    def update(self):
        self.health_boost = 5
        self.attack_boost = 3
        self.defense_boost = 2
        self.evolve = 10

    def __str__(self):
        self.update()
        return "Pokemon name: {}, Type: {}, Level: {}".format(self.name, self.p_type, self.level)

    def opponent(self, p_type):
    if self.ptype == "Grass":
        return ("Fire", "Water")
    elif self.p_type == "Ghost":
        return ("Dark","Psychic")
    elif self.p_type == "Fire":
        return ("Water","Grass")
    else :
        return ("Electric","Fighting")




class Grass_Pokemon(Pokemon):
    attack = 15
    defense = 14
    health = 12
    p_type = "Grass"

    def update(self):
        self.health_boost = 6
        self.attack_boost = 2
        self.defense_boost = 3
        self.evolve = 12



class Ghost_Pokemon(Pokemon):
    p_type = "Ghost"

    def update(self):
        self.health_boost = 3
        self.attack_boost = 4
        self.defense_boost = 3

    def opponent(self):
    if self.p_type == "Ghost":
        return ("Dark", "Psychic")

class Fire_Pokemon(Pokemon):
    p_type = "Fire"



class Flying_Pokemon(Pokemon):
    p_type = "Flying"

标签: python-3.x

解决方案


您可以使用包含优点和缺点的字典轻松完成,

def opponent(self):

    op = {'Grass': ['Fire', 'Water'], 'Ghost': ['Dark', 'Psychic'], 'Fire':['Water', 'Grass'], 'Flying': ['Electric', 'Fighting']}

    return tuple(op[self.p_type])

推荐阅读