Matg0d
Matg0d

Reputation: 29

List with constructors, whats the behavior?

Im trying to randomly generate objects and attach it to a set, but later code is behaving in some strange way, having duplicated objects(that is, objects that return the same number when id(x) is called). Soo my question is, on the code below, the "newanimal" is always a new instance or im repeating objects and changing they?

from random import randint, choice
Animals_to_choose = [Passaro(), Sapo(), Rato(), Coelho(), Cobra(), Tartaruga(), Lobo()] 
someset = set()
n_animals_to_create = 10

for number in range(n_animais_to_create):
    newanimal = choice(Animals_to_choose)
    newanimal.number = number
    someset.add(newanimal)

Just to point out, all these classes inherit these definitions:

def __hash__(self):
    return self.number
def __eq__(self, other):
    return self.number == other.number

Upvotes: 0

Views: 45

Answers (1)

g.d.d.c
g.d.d.c

Reputation: 48018

You should change your code like this:

from random import randint, choice
Animals_to_choose = [Passaro, Sapo, Rato, Coelho, Cobra, Tartaruga, Lobo] 
someset = set()
n_animals_to_create = 10

for number in range(n_animals_to_create):
    newanimal = choice(Animals_to_choose)()
    newanimal.number = number
    someset.add(newanimal)

The idea here is that you want the Classes in the choices set, but you want to instantiate a new one each time you sample the set.

Upvotes: 2

Related Questions