Function that returns a new instance of a class

Asked

Viewed 40 times

-1

Can anyone explain to me why this function is not returning a new instance. It returns a monster object exactly as I want, but when the monster dies, the new instance it returns comes back exactly like the old monster that has already been killed.

def new(self, name):
    monster = self._monsters.get(name) # Dicionário que contém todos os monstros
    instance = Monster(name=name) # Cria um novo monstro
    for attr in monster.__dict__:
        # Pega os atributos de um monstro existente o coloca na nova instância
        instance.__setattr__(attr, monster.__dict__[attr]) 
    return instance

1 answer

1


look - your whole project - does some strange things to manipulate objects - and the code is not all there, I went to see in github, because of the contact we had in another question - https://github.com/ThomasCaio/.RPG . And the problem is that their different monsters (with different "Names", should be classes different - you create everything as the same class, use instances for a type of monster - and still use a "caching" scheme to ensure that in fact there is only one instance "Monster" with the same "name" at a time.

Since the code is not all here (in question), nor have I done the full analysis, but probably the problem you are having provavelmetne is related to this approach.

(Putting almost all the project code in a question here also I think would not solve). Maybe you can even find the problem punctual there, but I did not find - except that the call to Monsterfactory.add on this line https://github.com/ThomasCaio/.RPG/blob/9f6f38a7d10303b0bed7de434a3c279c266d57ae/rpg/units.py#L346 should at least replace the "old monster" with the "new monster". If you’re trying to have two instances of a monster with the same "name", the problem is just there, the monster registry within "Monsterfactory" keeps only one monster of each "name" - but a new instance should come with the normal reset attributes.

  • Oops. Actually this version that is on Github it still returned right to new instance. The problem is, I’m fixing all this weird stuff and you’re screwing it up. Monster can have several instances, only the object that manipulates the monsters that I left to have only one instance, since in this object would be stored the monsters.

  • Ahh ok, I found it. The Monster class has a line that adds the monster to the name-based Factory and replaces the old monster.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.