NameError创建导入类的实例

时间:2019-10-21 14:04:50

标签: python class nameerror

我有一个Course类的子类,如下所示:

# course.py
class Course:
    """Represent a single Course"""
    kind = 'Gen Ed'
    def __init__(self, name, number) :
        self._name = name # 'private' instance variable\
        self._number = number
        self.__display()
    def display(self):
        print(self.kind,"Course:" , self._name, self._number, sep=" ")
    __display = display # private copy


class CSCourse(Course):
    """Represent a single CS Course"""
    kind = 'CS' # class variable shared by all CSCourses
    def __init__(self, name, number, language, numberOfPrograms):
        Course.__init__(self, name,  number)
        self._language = language
        self._numberOfPrograms = numberOfPrograms
    def display(self):
        Course.display(self)
        print('Language', self._language,
         'Number Of programs:', self._numberOfPrograms, sep = ' ')

我按如下所示导入模块:

>>>from course import *

这不会引发任何异常,但是当我发出以下命令来调用构造函数时,是否出现以下错误?

>>> cs360=CSCourse("Special Topics", 360, "python", 21)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined

请问我在做什么错?我也尝试查看导入的类中可用的方法。似乎什么都没有导入!

>>> import inspect
>>> inspect.getmembers(Course, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Course' is not defined
>>> inspect.getmembers(CSCourse, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined

1 个答案:

答案 0 :(得分:0)

对于遇到此问题的其他人,请检查您是否有循环导入(在文件 a.py from b import * 和文件 b.py from a import * 中)。发生这种情况时,Python 似乎不会引发异常,但导入不起作用。重构代码以删除循环导入为我解决了问题。