MVC programming with python (newbie) - please help

Gerard Flanagan grflanagan at yahoo.co.uk
Fri Jan 6 23:07:03 CET 2006


bwaha wrote:

> I'd appreciate some experience from the gurus out there to help me
> understand how to implement MVC design in python code.
>

I'm neither a guru nor an expert, have never used wxpython, and am not
qualified to advise on MVC!! But until someone more qualified arrives
here's some code from a relative newbie.
It's maybe not of any use in itself, but hopefully it won't lead you
astray either.

Hope it helps.

Gerard




######## Model ########
class Study(object):
    def __init__(self, name, file):
        self.name = name
        self.file = file

class Project(object):
    def __init__(self, name):
        self.name = name
        self.studies = []
######## End Model ########

######## View ########
class TreeViewNode(object):
    children = []
    tag = "NODE"

class StudyNode(TreeViewNode):
    def __init__(self, study):
        self.tag = study.name
        self.file = study.file
        self.children = None

class ProjectNode(TreeViewNode):
    def __init__(self, project):
        self.tag = project.name
        for study in project.studies:
            self.children.append( StudyNode(study) )

class ProjectTreeView(TreeViewNode):
    def __init__(self):
        self.tag = "All Projects"

    def add_node(self, node):
        assert isinstance( node, ProjectNode )
        self.children.append(node)
######## End View ########

data='''
BEGIN PROJECT "mpi6_0"
STUDY "Cyc0302_0" cyc0302_beanoz_x1.sdy
STUDY "Cyc0305_0" cyc0305_beanoz_x1.sdy
STUDY "Cyc0308_0" cyc0308_beanoz_x1.sdy
STUDY "Cyc0311_0" cyc0311_beanoz_x1.sdy
STUDY "Cyc0314_0" cyc0314_beanoz_x1.sdy
END PROJECT
BEGIN PROJECT "mpi6_1"
STUDY "Cyc0302_1" cyc0302_beanoz_x1.sdy
STUDY "Cyc0305_1" cyc0305_beanoz_x1.sdy
STUDY "Cyc0308_1" cyc0308_beanoz_x1.sdy
STUDY "Cyc0311_1" cyc0311_beanoz_x1.sdy
STUDY "Cyc0314_1" cyc0314_beanoz_x1.sdy
END PROJECT
'''

if __name__ == '__main__':
    import StringIO
    src = StringIO.StringIO(data)
    projects = []
    for line in src:
        parts = line.split(' ')
        begin = parts[0] == 'BEGIN'
        studyline = parts[0] == 'STUDY'
        end = parts[0] == 'END'
        if begin == True:
            project = Project( parts[2][1:-1] )
        elif studyline == True:
            project.studies.append( Study(parts[1][1:-1], parts[2]) )
        elif end == True:
            projects.append( project )

    for proj in projects:
        print 'PROJECT: ', proj.name
        for study in proj.studies:
            print '---- ', study.name

    MyTreeView = ProjectTreeView()
    for proj in projects:
        MyTreeView.add_node( ProjectNode(proj) )
    print MyTreeView




More information about the Python-list mailing list