Python Forum
Run a Function?: Trouble with Online Python Course
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Run a Function?: Trouble with Online Python Course
#1
Please help me with the below program. My Python is rusty. I'm trying to help my son with the below program. It should return a message like "Pichu (health: 30)", but it only returns nothing. Am I supposed to run a certain function?
What is missing?

class Pokemon():
    def __init__(self):
        self.name = ""
        self.health = 0
    def attack(self, other_pokemon):
        raise NotImplementedError(
            "Sorry, all subclasses have to write their own attack function!")
class Pichu(Pokemon):
    def __init__(self):
        self.name = "Pichu"
        self.health = 30

    def attack(self, other_pokemon):
        other_pokemon.health -= 2
        if other_pokemon.is_alive():
            print("Pichu ZAPPED {}, dealing 2 damage [{}]".format(
                other_pokemon.name, other_pokemon.health))
        else:
            print("Pichu ZAPPED {}, which faints".format(other_pokemon.name))
    def is_alive(self):
        if self.health > 0:
            return True
        else:
            return False

    return "{} (health: {})".format(self.name, self.health)
    def __str__(self):
        pass
    
Reply
#2
This part is not correct
    return "{} (health: {})".format(self.name, self.health)
    def __str__(self):
        pass
the __str__ method should return a string
change it to
    def __str__(self):
        return "{} (health: {})".format(self.name, self.health)
Then create an instance of Pichu and print it
pichu = Pichu()
print(pichu)
Output:
Pichu (health: 30)
Reply
#3
thank you! I'll try that
Reply
#4
I would use the abstract base class (abc) module. Declare "attack()" an abstract method and abc will raise an exception when you try to create an instance of an incomplete subclass instead of waiting to call the missing method. Plus you get a better error message.
import abc

class Pokemon(abc.ABC):
    def __init__(self, name="", health=0):
        # Using default arguments instead of hiding default values. Or don't use default arguments and
        # force the user into providing values for name and health.
        self.name = name
        self.health = health

    @abc.abstractmethod
    def attack(self, other_pokemon):
        """Attack another pokemon"""

    def is_alive(self):
        return self.health > 0

    def __str__(self):
        return f"{self.name} (health: {self.health})"


class Pichu(Pokemon):
    def __init__(self):
        # Call superclass __init__().  Push up as much as you can to the superclass.
        super().__init__("Pichu", 30) 

    def attack(self, other_pokemon):
        other_pokemon.health -= 2
        if other_pokemon.is_alive():
            print(
                "Pichu ZAPPED {}, dealing 2 damage [{}]".format(
                    other_pokemon.name, other_pokemon.health
                )
            )
        else:
            print("Pichu ZAPPED {}, which faints".format(other_pokemon.name))


class BadMonster(Pokemon):
    """I am not a proper subclass of Pokemon because I don't have an attack method"""
    def __init__(self):
        super().__init__("Bad Monster", -1)


p = Pichu()
b = BadMonster()
Error:
Traceback (most recent call last): File "...", line 42, in <module> b = BadMonster() TypeError: Can't instantiate abstract class BadMonster with abstract method attack
Other comments:

Push commonality up. is_alive() is likely something all Pokemon support, an likely it will be the same for all Pokemon. Put this in the base class. Same goes for __str__().

Use super(). As is, your code will never call Pokemon.__init__(). You can either drop that method from Pokemon, or you can call it from the subclass __init__() methods.

name and health should be arguments in Pokemon.__init__(). I provided default arguments, but you might want to make these required arguments to the init.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trouble with installing python domingo251 2 605 Sep-23-2023, 12:03 AM
Last Post: ICanIBB
Question Embedding a python file online Dreary35 0 1,535 Jun-10-2021, 05:05 PM
Last Post: Dreary35
  python doc edit and run online? luckrill 0 1,589 Jul-09-2020, 01:28 PM
Last Post: luckrill
  Online python repl? Gribouillis 4 41,534 Apr-09-2020, 12:19 PM
Last Post: Gribouillis
  Trouble with list function Eggman72 2 1,746 Mar-23-2020, 09:36 PM
Last Post: Eggman72
  Using online python for course, How do I open a File that's a link? WhatsupSmiley 1 2,540 Mar-20-2020, 06:56 AM
Last Post: buran
  New to python, having trouble with an exercise Salkay 3 2,168 Feb-18-2020, 01:42 AM
Last Post: Salkay
  More Python Embedding Trouble jibarra 3 2,948 Jul-11-2019, 09:25 PM
Last Post: Gribouillis
  Trouble on importing function from astropy library samsonite 4 3,721 Mar-21-2019, 12:18 PM
Last Post: samsonite
  Trouble installing Python 3.5 (.4 and .0) GKK 1 2,334 Aug-17-2018, 11:34 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020