natureminded natureminded - 2 months ago 6
Python Question

Practicing Inheritance in Python: Why AttributeError, despite my class and attribute seem setup correctly?

I've got the following file/folder setup for my Python project (practicing inheritance) as follows:

my_project/new_classes.py
my_project/human/Human.py
my_project/human/__init__.py (note, this is a blank file)


Although it appears that my
class Samurai(Human)
is setup correctly, I'm receiving the following error:

line 41, in <module>
tom.sacrifice()
AttributeError: 'Samurai' object has no attribute 'sacrifice'


Here's the code from my
my_project/new_classes.py
file:

from human.Human import Human
class Wizard(Human):
def __init__(self):
super(Wizard, self).__init__()
self.intelligence = 10
def heal(self):
self.health += 10
class Ninja(Human):
def __init__(self):
super(Ninja, self).__init__()
self.stealth = 10
def steal(self):
self.stealth += 5
class Samurai(Human):
def __init__(self):
super(Samurai, self).__init__()
self.strength = 10
def sacrifice(self):
self.health -= 5
# create new instance of Wizard, Ninja, and Samurai
harry = Wizard()
rain = Ninja()
tom = Samurai()
print harry.health
print rain.health
print tom.health
harry.heal()
print harry.health
rain.steal()
print rain.stealth
tom.sacrifice()
print tom.health
print tom.stealth


The code breaks when it gets to line
tom.sacrifice()
- any ideas why?

One other question I had was at first, when trying to import the parent class, I was using the statement
from human import Human
, which I thought would work (as I thought the formula was from
module_directory import ModuleFileName
, but was receiving an error as follows:
TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given)
. I resolved this by changing my import statement to,
from human.Human import Human
and was wondering why this worked while the other did not? I may be confused about correctly importing classes and was hoping someone also might be able to help clarify.

[EDIT] Removed comments.

Answer

I resolved this by changing my import statement to, from human.Human import Human and was wondering why this worked while the other did not?

This is because the first "human" is your Python module (Human.py). The Human class is inside it, so that's why your import statement must be as you wrote last. You do not want to import the module, but the class.

As to your AttributeError problem, it's odd as your classes seem OK. It's probably something unusual inside the Human class. Can we have the code in it?

EDIT

I see you found the solution for the AttributeError problem so I'll leave the answer for the second problem only.