我创建了一个python包,即 package_demo ,它有三个python模块 init .py , employee.py 和 manager.py 。
employee.py: -
def topSalary_employee(salary_list):
return max(salary_list);
def leastSalary_employee(salary_list):
return min(salary_list);
def avarageSalary_employee(salary_list):
summation=0;
for salary in salary_list:
summation+=salary;
return summation;
manager.py: -
def topSalary_manager(salary_list):
return max(salary_list);
def leastSalary_manager(salary_list):
return min(salary_list);
def avarageSalary_manager(salary_list):
summation=0;
for salary in salary_list:
summation+=salary;
return summation;
初始化的.py: -
from manager import*;
from employee import*;
现在我想访问 manager.py 和 employee.py 的所有功能到另一个python模块,即 AAA.py ,这是位于包 package_demo 之外。这是AAA.py的代码
AAA.py: -
import package_demo
employee_salary_list = [12000,23000,18000,25000,8000,17000];
manager_salary_list = [32000,45000,28000,50000,38000,44000];
print("\t...Manager Salary Details...");
print("Highest salary of Manager : ",package_demo.topSalary_employee(manager_salary_list));
print("Lowest salary of Manager : ",package_demo.leastSalary_manager(manager_salary_list));
print("Average salary of Manager : ",package_demo.avarageSalary_manager(manager_salary_list));
print("\t...Employee Salary Details...");
print("Highest salary of Employee : ",package_demo.topSalary_employee(employee_salary_list));
print("Lowest salary of Employee : ",package_demo.leastSalary_employee(employee_salary_list));
print("Average salary of Employee : ",package_demo.avarageSalary_employee(employee_salary_list));
但是当我运行AAA.py程序时,它会显示一些错误,如下面的
Traceback (most recent call last):
File "F:\Document\Files\Coding\Java Eclipse\Python Project\First Project\src\AAA.py", line 1, in <module>
import package_demo
File "F:\Document\Files\Coding\Java Eclipse\Python Project\First Project\src\package_demo\__init__.py", line 1, in <module>
from manager import*;
ImportError: No module named 'manager'
答案 0 :(得分:3)
所有导入都是从您启动Python的目录中进行评估的,因此当init.py尝试导入管理器时,Python将尝试从您当前所在的目录中查找,而不是从init.py所在的目录中查找。 / p>
您要使用相对导入或将导入转换为绝对导入:
相对
from .manager import*;
from .employee import*;
绝对值:
from package_demo.manager import*;
from package_demo.employee import*;