On 20/12/15 00:48, jamie hu wrote: > trying to think/implement. I can create a given student object based on > given firstname, lastname and grade. How do I find all objects matching > particular criteria and return them to caller? Do I need to iterate/select > through some list/database and create Student objects again?
You need to store a referejce to each object in some kind of container - a list or dictionary for example, or maybe a full blown database. > class Student(): > * def __init__(self,firstname,lastname,age): > * * self.firstname = firstname > * * self.lastname = lastname > * * self.grade = grade > > * def set_grade(self,grade): > * * self.grade = grade > > * @classmethod > > * # Find all Students with given lastname > * def find_by_lastname(): > * * # How do I return all student objects that have same lastname? > * * # Do I need to call init method again? I am confused here. > * * pass You don't need to call init a second time but you do need to put your instances into a container as you create them. A common way to do this is to have a class attribute (ie not an instance one) called _instances or similar and have a line at the end of __init__() that does Student._instances.append(self) Your class method can then traverse the _instances collection checking each instance until it finds the desired object. If you have many objects, and especially if they will not all be instantiated at once you would use a database and in that case the class method would check the instances collection first to see if you already had the object in memory and, if not, instantiate it from the database. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor