导入类时的错误

0 投票
1 回答
28 浏览
提问于 2025-04-11 22:12

我在导入类的时候遇到了一些问题(请看我下面的代码)。

这是文件 admin_instance.py 的代码,我发现 admin_instance.py 中的 admin 下面有一条波浪线。

import admin

my_admin = admin.Admin('john', 'doe', 30, 'USA')
my_admin.describe_user()
my_admin.admin_privileges.show_privileges()

这是 admin.py 的代码。

class User:
    def __init__(self, first_name, last_name, age, location):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.location = location

    def describe_user(self):
        print(f"The full name of the user is {self.first_name.title()} {self.last_name.title()}." 
              f" He is {self.age} years old and he is from {self.location}.")

    def greet_user(self):
        print(f"Hello, {self.first_name.title()} {self.last_name.title()}!")

class Privileges:
    def __init__(self, privileges = ['can add post', 'can delete post', 'can ban user']):
        self.privileges = privileges

    def show_privileges(self):
        print("Administrator's set of privileges are: ", sep = "", end = " ")
        for x in self.privileges:
            print(x, end = " ")

class Admin(User):
    def __init__(self, first_name, last_name, age, location):
        super().__init__(first_name, last_name, age, location)
        self.admin_privileges = Privileges()

我的代码是在 VS Code 中运行的,但它提示说 Import 'admin' could not be resolved Pylance (reportMissingImports) [Ln 1, Col 8]

我的两个文件在同一个文件夹里,所以我不太明白问题出在哪里。请帮我解决这个问题!请看下面的截图。

enter image description here

1 个回答

1

你打开的项目文件夹并不是“admin.py”和“admin_instance.py”的父文件夹(否则“admin.py”的路径应该是相对路径,而不是“c: > ...”)。所以这些文件被当作独立的Python代码文件来处理。

你可以在VScode的菜单中选择“文件” -> “打开文件夹”,然后打开“C:...\Python work\importing”,这样你就能看到区别了。

撰写回答