[Tutor] Playing with generators

Alan Gauld alan.gauld at yahoo.co.uk
Fri Aug 12 12:13:33 EDT 2022


On 10/08/2022 12:32, Leam Hall wrote:
> I'm wondering if there's a way to combine "make_person" with the generator 

I'm not certain I really understand your objective here but I will offer
an alrtrnative to your approach which is how i would tend to do this.
(And apologies I've been away from civilisation for a few days so am in
catch up mode)


> data = [
>      { 'fname':'Wilbur', 'lname':'Lefron' },
>      { 'fname':'Al', 'lname':'Lefron' },
>      { 'fname':'Jo', 'lname':'Franco' },
>      { 'fname':'Mon', 'lname':'Pascal' },
>      { 'fname':'Gray', 'lname':'Webb-Marston'},
>      ]

> class Person():
>      def __init__(self, data = {}):
>          self.fname = data.get('fname', 'fred')
>          self.lname = data.get('lname', 'frank')
> 
> 
> def make_person(data):
>      ps = ( Person(d) for d in data)
>      return ps

This creates and returns a tuple of Person objects.


>          
> peeps = {}
> 
> for fname, peep in ( (p.fname, p) for p in make_person(data) ):
>      peeps[fname] = peep

This then creates a dictionary of those same objects
keyed by name.

One of the snags with this is that objects other than
the person have to know and store data that is inside
the person - thats a bad smell OOP wise!

Why not create the dict as a class variable and add
the objects to it as they are created:


class Person:
    peeps = {}
    def __init__(self, data = {}):
       self.fname = data.get('fname', 'fred')
       self.lname = data.get('lname', 'frank')
       Person.peeps[self.fname] = self

> for person in peeps.values():
>      print(person.lname)

becomes:

for person in Person.peeps:
    print (person.lname)

That way nobody outside the class has to know the
internal data. Objects should manage themselves...

Doesn't really address anything about generators
except to say that generatots here may be a bad idea?


-- 
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




More information about the Tutor mailing list