[Tutor] Is this a good idea?

Kent Johnson kent37 at tds.net
Tue Jun 5 14:43:59 CEST 2007

Carlos wrote:
> Hello,
> I'm trying to generate two classes, one of them is a given object and 
> the other is a 'factory' of those objects. I'm doing this because I'm 
> working with huge amounts of objects and would like to have a loop 
> generating them. The problem is that I fear that my understanding of OOP 
> is just not good enough. So what do you say, is this a good way to solve 
> this??
> class objct:
>    def __init__(self, name, val):
>        self.name = name
>        self.val = val
>       class collection:

This indent is funny; I assume this is a top-level class, not a nested 
>    def __init__(self, objcts):
>          objecList = []
>        for i in range(objcts):
>            instance = 'myInst%i' %(i)
>            objecList.append(instance)
>        for i in range(objcts):
>            i = objct(objecList[i], i)
>            print i.name
>            print i.val
>   myC = collection(10)

The idea is OK but the implementation is flawed. collection() can be a 
standalone factory function, it doesn't have to be a class. (You could 
make it a staticmethod if you want it to be enclosed in the objct 

Note that objecList is a list of instance names, not a list of objct 
instances. The objcts you create in the second loop are just thrown 
away. Actually objecList is also thrown away since it is never assigned 
to an instance variable; myC refers to an instance of collection but it 
has no instance data.

If you want to create a list of objcts you can do this in a single list 

myC = [ objct('myInst%i' %(i), i) for i in range(objcts) ]

You could put this in a collection() function if you like. I would write 
your example as

class objct:
    def __init__(self, name, val):
        self.name = name
        self.val = val

def objct_collection(num):
     return [ objct('myInst%i' %(i), i) for i in range(num) ]

I hope the real code uses more descriptive names than objct and 


More information about the Tutor mailing list