Create a simple example
Assume we run ls -R
in the current working directory and this is the result:
./second_karma:
enemy.py import.py __init__.py math
./second_karma/math:
fibonacci.py __init__.py
And we run this command $ python3 second-karma/import.py
init.py is an empty file but it should exists.
Now let's see what is inside the second-karma/import.py
:
from .math.fibonacci import Fibonacci
fib = Fibonacci()
print(fib.get_fibonacci(15))
And what is inside the second_karma/math/fibonacci.py
:
from ..enemy import Enemy
class Fibonacci:
enemy: Enemy
def __init__(self):
self.enemy = Enemy(150,900)
print("Class instantiated")
def get_fibonacci(self, which_index: int) -> int:
print(self.enemy.get_hp())
return 4
Now the last file is second_karma/enemy.py
:
class Enemy:
hp: int = 100
attack_low: int = 180
attack_high: int = 360
def __init__(
self,
attack_low: int,
attack_high: int) -> None:
self.attack_low = attack_low
self.attack_high = attack_high
def getAttackPower(
self) -> {"attack_low": int, "attack_high": int}:
return {
"attack_low": self.attack_low,
"attack_high": self.attack_high
}
def get_hp(self) -> int:
return self.hp
Now a simple answer why it was not working:
- Python has a concept of packages, which is basically a folder containing one or more modules, and zero-or-more packages.
- When we launch python, there are two ways of doing it:
- Asking python to execute a specific module (
python3 path/to/file.py
).
- Asking python to execute a package.
- The issue is that
import.py
makes reference to importing .math
- The
.math
in this context means "go find a module/package in the current package with the name math"
- Trouble:
Important note:
Those __init__.py
are necessary and if you have not them you must create them first.
An example in github