Python 3.6.1类对象导入遇阻:PyStudentManager应用导入问题求助
Hey there! Let's work through this import problem step by step. Since your Pluralsight course uses an older Python version, the main hiccup is likely differences in how Python handles relative vs absolute imports between versions (2.x vs 3.x), plus making sure your project structure is set up correctly.
First, let's break down the most common project setups and their corresponding import fixes:
Case 1: Classes and Web App are in the Same Folder
If your project looks like this:
PyStudentManager/ ├── classes.py └── webapp.py
This is the simplest scenario, and it works consistently across most Python versions. In webapp.py, use this straightforward import:
# Import just HighSchoolStudent from classes import HighSchoolStudent # Or import both Student and HighSchoolStudent if you need both from classes import Student, HighSchoolStudent
Double-check that classes.py defines the classes correctly, like this:
class Student: # Your Student class logic here class HighSchoolStudent(Student): # Your HighSchoolStudent subclass logic here
Case 2: You're Working with a Package Structure
If your project is organized as a proper Python package (with an __init__.py file), like this:
PyStudentManager/ ├── myapp/ │ ├── __init__.py │ ├── classes.py │ └── webapp.py
Here's where older vs newer Python versions differ:
- Older Python (2.x): Allowed implicit relative imports, so
from classes import HighSchoolStudentwould work out of the box. - Python 3.x: Requires explicit relative imports (using a dot) or absolute imports. Use either:
# Explicit relative import (same package) from .classes import HighSchoolStudent # Absolute import (using the package name) from myapp.classes import HighSchoolStudent
Common Troubleshooting Tips
- Check Filenames/Spelling: Make sure you didn't mistype
classes.py(e.g.,class.pyorClasses.py—note that Linux/macOS is case-sensitive!). - Fix Script Execution Errors: If you run
webapp.pydirectly as a script (python webapp.py) and get relative import errors, you can add your project root to Python's path temporarily:import sys from pathlib import Path # Add the parent folder of webapp.py to the path sys.path.append(str(Path(__file__).parent)) from classes import HighSchoolStudent - Verify Class Inheritance: Ensure
HighSchoolStudentactually inherits fromStudentinclasses.py—a missing parent class in the definition would cause import issues too!
内容的提问来源于stack exchange,提问作者Christopher Roper

