hi!

I have another struggle. I'd like to have this kind of output:
som object studenta: Janko Mrkvicka
som object predmetu: fyzika, mam znamky: [4, 1] a priemer: 2,5

How can I make it?

my output is a bit different (it is in last line):

som object studenta: Janko Mrkvicka
som object predmetu: fyzika, mam znamky: [4, 1] a priemer: 0
som object predmetu: english, mam znamky: [1] a priemer: 0
som object predmetu: matematika, mam znamky: [] a priemer: 0
2
None
-----------------------------------------------------
som object studenta: Janka Vaskova
som object predmetu: dejepis, mam znamky: [1, 2, 3] a priemer: 0
som object predmetu: biologia, mam znamky: [] a priemer: 0
som object predmetu: english, mam znamky: [] a priemer: 0
som object predmetu: fyzika, mam znamky: [1] a priemer: 0
1
None
here is a complete code:

class Cstudent():
    def __init__(self, name):
        self.name = name
        self.predmety = []
        self.mark = []
        self.absence = 0

    def add_subject(self, predmet):
        self.predmety.append(predmet)

    def add_mark(self,predmet,mark):
        for i in self.predmety:
            if i.nazov == predmet:
                i.add_znamka(mark)

    def priemer_predmet(self,predmet):
        for i in self.predmety:
            if i.nazov == predmet:
                i.average_predmet(predmet)

    def __str__(self):
        #return self.name
        #return 'som objekt studenta: ' + (self.name)
        return 'som object studenta: %s'% (self.name)

    def print_zoznam_predmetov(self):
        lst = []
        for prd in self.predmety:
            lst.append(str(prd))
        return '\n'.join(lst)
        #return '\n'.join(lst)


class Cpredmet():
    def __init__(self, nazov):
        self.nazov = nazov
        self.znamky = []
        self.priemer = int()

    def add_znamka(self, znamka):
        self.znamky.append(znamka)

    def average_predmet(self, predmet):
        p=sum(self.znamky) / len(self.znamky)
        print p


    def __str__(self):
        #return self.nazov
        return 'som object predmetu: %s, mam znamky: %s a priemer: %s' % \
            (self.nazov, str(self.znamky), self.priemer)

def main():

# inicalizacia objektu student:
#-------------------------------
    janko = Cstudent('Janko Mrkvicka')
    janka = Cstudent ('Janka Vaskova')

# pridanie predmetu danemu objektu:
#-------------------------------
    janko.add_subject(Cpredmet('fyzika'))
    janko.add_subject(Cpredmet('english'))
    janko.add_subject(Cpredmet('matematika'))

    janka.add_subject(Cpredmet('dejepis'))
    janka.add_subject(Cpredmet('biologia'))
    janka.add_subject(Cpredmet('english'))
    janka.add_subject(Cpredmet('fyzika'))

# predanie znamky danemu objektu:
#-------------------------------
    janko.add_mark(predmet='fyzika',mark=4)
    janko.add_mark(predmet='fyzika',mark=1)
    janko.add_mark(predmet='english',mark=1)

    janka.add_mark(predmet='dejepis',mark=1)
    janka.add_mark(predmet='dejepis',mark=2)
    janka.add_mark(predmet='dejepis',mark=3)
    janka.add_mark(predmet='fyzika',mark=1)

# output:
#-------------------------------
    print janko
    print janko.print_zoznam_predmetov()
    print janko.priemer_predmet('fyzika')
    print '-----------------------------------------------------'
    print janka
    print janka.print_zoznam_predmetov()
    print janka.priemer_predmet('fyzika')


if __name__ == '__main__':
    main()

Recommended Answers

All 5 Replies

Well, apparently, this approach of classes may cause some inconvenients due to the fact that it's not the brightest approach.

Try to define some functions which will print that things for you, from inside the class, use some functions to add elements to the class, then, in the main function, to call accordingly to class calls the actual class and the print functions inside that class.
One final thought: Use a run() function inside the class to gather all the functions needed in this process, so that you would have to call only 1 function from the class in the main function.
Here's some information about classes:
http://docs.python.org/tutorial/classes.html#classes
If you need further information, or if there're any misunderstandings regarding this topic feel free to post them here...

Well, apparently, this approach of classes may cause some inconvenients due to the fact that it's not the brightest approach.

Try to define some functions which will print that things for you, from inside the class, use some functions to add elements to the class, then, in the main function, to call accordingly to class calls the actual class and the print functions inside that class.
One final thought: Use a run() function inside the class to gather all the functions needed in this process, so that you would have to call only 1 function from the class in the main function.
Here's some information about classes:
http://docs.python.org/tutorial/classes.html#classes
If you need further information, or if there're any misunderstandings regarding this topic feel free to post them here...

ok, I don´t know if this my example is good approach or not. I am learning it by using exercices... In a book, I foud out that there is not a lot of examples. For me exmples works!
Pls give me an example to what is a good approach. If I see it I will learn it much easy way.

Ok. I've looked upon your request. Here's an example of a program which stores Men.
I know, there is some logical error, and it will not store them in a file, but it's ok, it actually doesn't matter, as long as u get the point.
In order for this program to work, you need to place an empty .txt file in the same directory as this script, otherwise your screen will be filled by errors.
The .txt file should be called 'man.txt'.
Ok, here's the code:

'''
Created on Feb 23, 2012

@author: sin
'''
class Man:
    """
    The basic elements from this script.
    Having here the essential functions, on which all the program will be built.
    """
    def __init__(self, id, name, age):
        self.id = id
        self.name = name
        self.age = age
        
    def getid(self):
        return self.id
    
    def getname(self):
        return self.name
    
    def getage(self):
        return self.age
    
class ValidatorException(Exception):
    """
    Needed by the Validator Class
    """
    def __init__(self, errors):
        self.errors = errors

    def getErrors(self):
        return self.errors

class Validator:
    """
    Will report if there are any errors throughout the program.
    (It's not well developed, made this in like 20 minutes, it can hold further restrictions.)
    THERE ARE ALOT OF BUGGS @ THIS PROGRAM, BEAR wih me:d heh
    """
    def ManValidate(self, mn):
        errors = []
        if (mn.id == ""): errors.append("Man's Id can't  be empty.")
        if (mn.name == ""): errors.append("Man's name can't be empty.")
        if (mn.age == ""): errors.append("Man's age can't be empty.")
        if len(errors) > 0:
            raise ValidatorException(errors)
        
class RepositoryException(Exception):
    pass

class RepMemory:
    """
    The actual 'memory' of the script, called also 'repository'
    Will hold the informations.
    """
    def __init__(self, validator):
        self.man = {} #We use a dictionary for the volatile memory.
        self.validator = validator 

    def StoreMan(self, mn):
        if mn.getid() in self.man:
            raise RepositoryException

        if (self.validator != None):
            self.validator.ManValidate(mn)

        self.man[mn.getid()] = mn
        
    def ManSize(self):
        return len(self.man)

    def getAllMan(self):
        return self.man.values()[:]

class ManRep(RepMemory):
    """
    Used in reading/writing the file.
    """
    def __init__(self, validator, filename):
        RepMemory.__init__(self, validator)
        self.filename = filename
        self._loadfromfile()

    def _loadfromfile(self):
        fh = open(self.filename)
        for line in fh:
            fields = line.split(" ")
            mn = Man(fields[0], fields[1], fields[2])
            self.man[mn.getid()] = mn
        fh.close()

    def MnStore(self, mn):
        RepMemory.StoreMan(self, mn)
        self.mnappendfl(mn)

    def mnapendfl(self, mn):
        fh = open(self.filename, "a")
        fh.write("Man id", "Man Name", "Man Age\n")
        str = mn.getid() + " " + mn.getname() + " " + mn.getage()
        fh.write("\n")
        fh.write(str)
        fh.close()

class ManController:
    """
    Gathers the info introduced by the user in the Console Class and pass them to the memory class.
    """
    def __init__(self, rep, validator):
        self.rep = rep
        self.validator = validator

    def createMan(self, id, name, age):
        """
        Will create the men, with the informations introduced in the Console class.
        Level 2 of approach.
        """
        mn = Man(id, name, age)

        if (self.validator != None):
            self.validator.ManValidate(mn)

        self.rep.StoreMan(mn)
        return mn

    def findMan(self, str1):
        """
        Search for the requested man. Level 2 as of user approach to the program.
        """
        all2 = self.rep.getAllMan()
        rez = []
        for mn in all2:
            if (mn.getname().find(str1) == 0):
                rez.append(mn)
        return rez
      
    def getname(self):
        self.getname = Man.getname(self)
        
class Console:
    """
    Class which contains the 1st level as of user approach to the actual program.
    """
    def __init__(self, ctr1):
        self.ctr1 = ctr1
    
    def showUI(self):
        print """                Main Menu
1. Add man
2. List men
'menu' to list the menu
'exit' to exit
"""
        while True:
            cmd = raw_input("Insert command: ").strip()
            if cmd == "1." or cmd == '1':
                self.readMan()
            if cmd == "2." or cmd == '2':
                self.listMan()
            if cmd == "exit":
                exit()
            if cmd == "menu":
                self.showUI()
    
    def readMan(self):
        """
        Will gather the information: 1st level as approach to user.
        """
        id = raw_input("Write the id of the man: ").strip()
        name = raw_input("Write the name of the man: ").strip()
        age = raw_input("Write the age of the man: ").strip()
        try:
            mn = self.ctr1.createMan(id, name, age)
            print "Mr. " + mn.getname() + " is saved into our database."
        except RepositoryException:
            print "Duplicate man id."
        except ValidatorException, ex:
            print ex.getErrors()

    def listMan(self):
        '''Will list all the men in the memory.'''
        str = raw_input("Insert the desire initial of the man, or the whole name of the man.")
        man = self.ctr1.findMan(str)
        print "Men:" "\n" " %4s %20s %20s" % ("Man Id", "Man Name", "Man Age")
        for mn in man:
            print " %4s %20s %20s" % (mn.getid(), mn.getname(), mn.getage())
            
            
'''
Gathering all together:
'''

validator = Validator()
rep = RepMemory(validator)
rep = ManRep(validator, "man.txt")
ctr1 = ManController(rep, validator)
class menuz:
    def console_start_up(self):
            """Console start-up"""
            ui = Console(ctr1)
            ui.showUI()
            

menus = menuz()
menus.console_start_up()

I've added some info along the script.
I know there are a lot of bugs @ this script, but I don't have time to look into it (made in like top 20 min).
This is a model to view your program, a method of build bottom-top, starting with the lowest parts, and building the program to the actual single command of run() for example.

uuups! ok,thanks! - but it seems to be complicated....
my level in classes is not such high.

I've just given u an example, just look at the last classes, the console or the menuz, and see how I gathered all my information, to single line functions... That was my point...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.