[Tutor] Object oriented design
jamie hu
jamiehu17 at yandex.com
Mon Dec 21 19:14:17 EST 2015
*
*
20.12.2015, 01:25, "Alan Gauld" <alan.gauld at btinternet.com>:
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 objectld
in memory and, if not, instantiate it from the database.
HTH
--
Alan G
*
*
Thanks Alan. I was thinking about making a list of objects and search
through it, but wasn't sure if that was right way.
*
I wasn't sure instantiation needed when using database, but it seems like
that's the way. So ORM libraries do this work (fetch data and return
instantiated objects) behind the scenes??
*
--
Thanks,
Jamie
*
More information about the Tutor
mailing list