[Tutor] class attribute to initiate more classes
Dave Angel
davea at ieee.org
Sat Oct 31 12:55:12 CET 2009
Vincent Davis wrote:
> I have a program that generates many instances of a class with an attribute
> self.x = random.gauss(10, 2). So each instance has a different value for
> self.x. This is what I want. Now I want to make a class that starts my
> program and sets the attributes.
> class people:
> def __init__(self, size)
> self.size = size
>
> class makepeople:
> def __init__(self, randomsize)
> self.rsize = randomsize
> self.allpeople = []
> def makethem():
> for x in range(1,100):
> p+str(x) = people(self.rsize)
> allpeople.append(p+str(x))
>
> so what I would like to have work is set the attribute of makepeople so that
> when it is used to make instances of people each will have a different size.
>
> listofp = makepeople(random.guass(100, 2))
> listofp.makethem()
>
> I would then what listofp.allpeople to be a list of people with different
> sizes. The above code does not work, I don't think it does anyway.
>
> I hope this makes sense, I am sure there is a term for what I am trying to
> do but I don't know it.
>
> Thanks
> Vincent Davis
>
>
You're trying to do several things here, and I'm unclear on many of the
details. So here's a new spec, and the implementation for it.
We want a factory class, which can be given a particular distribution
function and parameters, and using those parameters generate a list of
Person objects, whose heights are distributed according to that random
function. There might be duplicates in that list, but they'd be random
coincidence, and the list as a whole would be as random as the function
specified by the caller.
I also took a few liberties on the names of things, trying to use Python
conventions for naming, and things like using a singular word for a
classname of a single item. And I removed the allpeople attribute, as
the class only makes sense to me if you can use its instance multiple
times, to generate more items with the same given distribution.
CODE----
import random, functools
class Person:
def __init__(self, size):
self.size = size
def __str__(self):
return "Person of size %s" % self.size
class MakePeople:
def __init__(self, random_func):
self.random_func = random_func
def make_them(self, count):
return [Person(self.random_func()) for i in xrange(count)]
people_maker = MakePeople(functools.partial(random.gauss, 100, 2))
persons = people_maker.make_them(100)
for person in persons:
print person
/CODE---
DaveA
More information about the Tutor
mailing list