I am fairly new to coding and Python and I’m facing an issue with importing a class from one Python file to another. The files employee_1.py and company_1.py are in the same directory, but I keep getting an ImportError. Here are the details:
Directory Structure:
C:UserstrandOneDriveDesktopPython CourseClass and object1
│
├── employee.py
└── company.py
Content of employee_1.py:
print("Executing employee.py")
class Employees:
def __init__(self, fname, lname, salary):
self.fname = fname
self.lname = lname
self.salary = salary
def calculate_paycheck(self):
return self.salary/52
Content of company_1.py
from employee import Employees
class Company:
def __init__(self):
self.employees = []
def add_employee(self, new_employee):
self.employees.append(new_employee)
def display_employees(self):
print("Current Employees:")
for i in self.employees:
print(i.name, i.lname)
print("___________________")
def main():
my_company = Company()
employee1 = Employees("Sarah", "Holder", "50000")
my_company.add_employee(employee1)
employee2 = Employees("Sam", "Taylor", "244000")
my_company.add_employee(employee2)
employee3 = Employees("Danny", "Hans", "20000")
my_company.add_employee(employee3)
my_company.display_employees
main()
When I run company_1.py, I get the following error:
ImportError: cannot import name ‘Employee’ from ’employee_1′ (c:UserstrandOneDriveDesktop)
I have also done the following:
-
Verified Directory Structure so both employee_1.py and company_1.py are in the same directory.
-
Cleared Bytecode Files: Removed any pycache directories to ensure no stale bytecode is causing issues.
-
Correct Import Statement: Ensured that company_1.py is correctly importing Employee from employee_1.
Would really appreciate any help from you guys!
Son kuppo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.