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

sim*_*ail 6 python storage class instances

我试图了解在应用程序中存储类实例的最佳方式是什么,以便我正确访问属性并正确调用每个类方法。我希望该解决方案能够与 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)
Run Code Online (Sandbox Code Playgroud)

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

我找到的所有文章都谈到了类创建,但我找不到任何有关将其全部放在应用程序中和“类实例管理”、存储多个类实例(具有一对多或多对多链接)的内容同时)不同类型的课程。

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

sim*_*ail 4

好的,我明白了。类实例可以存储在其他类实例中的列表/字典类型的属性中(例如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()
Run Code Online (Sandbox Code Playgroud)

因此,在第二次分配(给 Binder)之后,复制的实际上只是对内存地址的引用。

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

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