Skip to main content
 首页 » 编程设计

python之在 python 应用程序中存储类实例的正确方法

2025年05月04日16bhlsheji

我试图了解在应用程序中存储类实例的最佳方式是什么,以便我可以正确访问属性并正确调用每个类方法。我希望解决方案与 ORM 一起工作,即 SqlAlchemy,并在最后添加 GUI。

假设我有笔记本课。还有可以属于一个笔记本的 Note 类。还有一个 Picture 类 - 它的实例可以出现在属于不同 Notebook 实例的多个 Notes 中。

现在我想到了下面的方法(我已经让它更简单/没有 ORM 只是为了理解这个想法):

class Notebook(object): 
    def __init__(self): 
        self.notesid=[] 
 
    def view_notes(self,notes,pictures): 
        for key,item in notes.items(): 
            if key in self.notesid: 
                item.show(pictures) 
 
class Note(object): 
    def __init__(self,id,content,picture): 
        self.id = id 
        self.content = content 
        self.picturesid = [picture.id] 
    def show(self,pictures): 
        print(self.id, self.content) 
        for item in pictures: 
            if item.id in self.picturesid: 
                print(item) 
 
class Picture(object): 
    def __init__(self,id,path): 
        self.id = id 
        self.path = path 
    def __str__(self): 
        '''shows picture''' 
        return "and here's picture %s" % (self.id) 
 
# main program 
 
notesdict={} 
pictureslist=[] 
 
notebook1=Notebook() 
picture1 = Picture('p1','path/to/file') 
note1=Note('n1','hello world',picture1) 
 
notesdict[note1.id] = note1 
pictureslist.append(picture1) 
notebook1.notesid.append(note1.id) 
 
notebook1.view_notes(notesdict,pictureslist) 

我不确定这是否是正确的方法,因为即使在这个简单的示例中,我也需要将所有字典/实例容器放入 view_notes() 方法中。感觉必须有一种更简单/更不容易出错的方法。

我找到的所有文章都说了类创建,但我找不到任何关于将它们放在应用程序和“类实例管理”中的任何内容,存储多个类实例(一对多或多对-同时有许多链接)不同种类的类。

您能否通过使用上面的代码/文章/书籍的链接来指导我正确的思考/方法?

请您参考如下方法:

好的,我明白了。 类实例可以存储在其他类实例中的列表/字典类型的属性中(例如Notebook实例中的Note实例)。

要记住的重要一点是,实际存储的是该属性是对位于 RAM 内存中特定地址下的实例的引用,而不是直接实例。

考虑一下:

class Notebook(object):     
     def __init__(self, iteminstance): 
        self.lista = [iteminstance] 
     def show(self): 
        print('Container1 list:') 
        for item in self.lista: 
            print(item.content) 
 
class Binder(object):     
     def __init__(self, iteminstance): 
        self.lista = [iteminstance] 
     def show(self): 
        print('Container2 list:') 
        for item in self.lista: 
            print(item.content) 
 
class Note(object):     
    def __init__(self, txt):     
        self.content = txt     
 
# create Notebook instance and store Note instance in 'lista' list argument     
a=Notebook(Note(5))     
a.show()     
 
# assign the same Note instance to different container, Binder instance     
b=Binder(a.lista[0])     
b.show() 
 
# check if both containers include the same object     
print(a.lista==b.lista) 
>>>True 
 
# change content of the Note instance via Notebook instance     
a.lista[0].content = 10 
 
# check if content has changed in both Notebook and Binder instances  
a.show()     
b.show() 

所以在第二次赋值(到 Binder)之后,被复制的实际上只是对内存地址的引用。

因此,存储对象(在本例中为 Note)中的每个更改都可以通过每个 Container 访问。 我原以为第二次赋值会复制当前状态的实例 - 但事实并非如此。

感谢 hpaulj 提出正确的问题! 为了进一步阅读,我认为我需要查找“收藏类”。