1

How can i modify a copy of a class without the original class being changed as well?

when i have a class like this:

class enemymob:
    def __init__(self, name, level, damage, health, maxhealth, armour):
        self.name = name 
        self.level = level
        self.damage = damage
        self.health = health
        self.maxhealth = maxhealth
        self.armour = armour

Goblin = enemymob("Goblin", 1, 10, 50, 50, 5)

and then i set enemy = Goblin:

enemy = Goblin

when i modify the value of the enemy, it also changes the value of the instance goblin as well. But for my code i need the instance Goblin's values to stay the same, and only change the value for it's copy, the enemy. How can i do that?

enemy.damage += 100
print(enemy.damage)
print(Goblin.damage)

110                                                                                                                                                                                                 
110                                                                                                                                                                                                 


Process exited with code: 0
pythonsohard
  • 127
  • 9

4 Answers4

2

The statement enemy = Goblin makes the enemy variable point to the same instance as the Goblin variable. If you want a new instance you can manipulate independently, you'd have to copy it, e.g., by using the copy module:

import copy
enemy = copy.copy(Goblin)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

You can use deepcopy to make the copy of the object -

from copy import deepcopy

enemy = deepcopy(Goblin)
Vedang Mehta
  • 2,214
  • 9
  • 22
0

The problem is that Goblin and enemy are pointing to the same thing. When you do Goblin = enemymob("Goblin", 1, 10, 50, 50, 5) followed by enemy = Goblin both enemy and Goblin will end up pointing to the same object.

kjschiroo
  • 500
  • 5
  • 10
0

In this case you set both your variables, enemy and Goblin to the same object. Create two object like that:

enemy = enemymob("enemy", 1, 10, 50, 50, 5)
Goblin = enemymob("Goblin", 1, 10, 50, 50, 5)
natschz
  • 1,007
  • 10
  • 23