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

2024-09-25 02:24:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图了解在应用程序中存储类实例的最佳方法,以便访问attributes权限并调用每个类方法权限。我希望解决方案能够与ORM一起工作,即SqlAlchemy,并在最后添加GUI。

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

现在我想到了下面的方法(我已经简化了/不使用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()方法中。感觉必须有一种更简单/不易出错的方法。

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

你能用上面的代码/文章/书籍的链接指导我正确的思考/方法吗?


Tags: path实例方法inselfiddef笔记本