Python - 无法访问类的实例

标签 python instances

我遇到了一个可能非常简单的问题,但我无法弄清楚。我正在尝试开发用于创建时间表的桌面应用程序。我正在使用 Tkinter 和 Python 3.6。我有一个 Teacher 类,因此用户可以创建具有各种属性的新实例。

class Teacher:
    """The properties of the teachers"""
    allTeachers = []
    def __init__(self, name, lessons, timeframe):
        self.name = name
        Teacher.allTeachers.append(self.name)
        self.lessons = lessons # number of lessons
        self.timeframe = timeframe

创建新实例后,我会检查它是否存在:

for obj in gc.get_objects():
    if isinstance(obj, Teacher):
        print(obj.name)

但是,当用户添加另一位老师时,上面的代码表示 Teacher 类仍然只有一个实例(最新的一个)。此外,当我从另一个模块(在同一目录中)运行相同的代码时,Python 告诉我 Teacher 类没有实例。尽管如此,类变量 (allTeachers) 会跟踪所有已添加的教师。

我是否遗漏了有关访问对象的一些基本知识?

最佳答案

如果您没有对您的实例持有任何引用,Python 会释放内存。您只存储老师的名字 - 而不是它的实例。所以如果你碰巧像这样创建它们:

Teacher("Hugo", None, "8am to 2pm")
Teacher("Claas", "some", "9am to 10am")

没有对实际实例的引用,它们会被垃圾收集。

可在此处阅读其他信息:Python garbage collector documentation


如果你想查找东西,如果你有超过 4 个项目,列表是不好的,他们得到了 O(n) 的查找。使用 setdict 代替 O(1)。如果你想通过名字查找 Teacherdict 会很方便:

class Teacher:
    """The properties of the teachers"""
    allTeachers = {} # dict as lookup  is faster then list for 4+ teachers
    def __init__(self, name, lessons, timeframe):
        self.name = name
        Teacher.allTeachers[self.name] = self  # store the instance under its name
        self.lessons = lessons # number of lessons
        self.timeframe = timeframe

    @classmethod
    def hasTeacher(cls,name):
        return name in Teacher.allTeachers


Teacher("Hugo", None, "8am to 2pm")
Teacher("Claas", "some", "9am to 10am")

import gc

print(Teacher.hasTeacher("Judith"))
print(Teacher.hasTeacher("Claas"))

for obj in gc.get_objects():
    if isinstance(obj, Teacher):
        print(obj.name)

输出:

False  # no teacher called Judith
True   # a teacher called Claas

# all the Teacher instances
Hugo
Claas

如果您以这种方式存储 Teacher 实例,您可能应该提供一种方法来按名称从类变量实例中删除它们 - 并可能从中按名称返回 Teacher - 实例

关于Python - 无法访问类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51463741/

相关文章:

java - 如何正确连接类(构造函数中的堆栈溢出)

python - 在 Windows 10 (python 3.6.2) 中安装 Tensorflow 时出现问题

python - Heroku 本地失败,没有错误消息

python - 架构 python 问题

微服务:数据库和微服务实例

go - 在 Golang 中返回一个新的 Struct 实例

python - 在另一个图像上匹配轮廓或绘制 (png) 轮廓

python - 使用脚本部分更新文档并添加缺少的字段

java - 将类的实例传递到另一个java文件中

Python:附加到存储在搁置字典中的实例所拥有的列表