Home > Enterprise >  OOP class AttributeError: 'Player' object has no attribute 'print_mana'
OOP class AttributeError: 'Player' object has no attribute 'print_mana'

Time:07-25

I'm quiet new to OOP in python, and I want to create a class that inherit other class methods, here is my code:

class setting_mana:
  def __init__(self,mana=30):
    self.print_mana = mana


class Player(setting_mana):
    def __init__(self, hit_points, sides):
        self.hit_points = hit_points
        self.sides = sides

    def take_hit(self):
        self.hit_points -= 2
        return self.hit_points

alexandre = Player(10,6)

alexandre.print_mana()

I want to inherit print_mana from the class setting_mana. How should I do it so the error: AttributeError: 'Player' object has no attribute 'print_mana' does not appear?

CodePudding user response:

There are two issues:

  1. You are attempting to use the attribute print_mana as a method when it's really an integer by the looks of it.
  2. print_mana (the attribute which I renamed to mana below) is not defined on instances of Player because you need to call the parent class constructor

I think what you want is something like this?

class ManaMixin:
    def __init__(self, mana=30):
        self.mana = mana

    def print_mana(self):
        print(self.mana)


class Player(ManaMixin):
    def __init__(self, hit_points, sides):
        super().__init__()
        self.hit_points = hit_points
        self.sides = sides

    def take_hit(self):
        self.hit_points -= 2
        return self.hit_points


p = Player(10, 6)
p.print_mana()  # prints 30

CodePudding user response:

Try using super(), call's the parent's __init__ function, allowing your Player class to have the print_mana attribute as well.

class setting_mana:
  def __init__(self,mana=30):
    self.print_mana = mana


class Player(setting_mana):
    def __init__(self, hit_points, sides):
        super().__init__() # Add this
        self.hit_points = hit_points
        self.sides = sides

    def take_hit(self):
        self.hit_points -= 2
        return self.hit_points

alexandre = Player(10,6)

print(alexandre.print_mana)

Output:

30
  • Related