Class add property on all objects in python

Viewed 37

I found an issue while programming on python. I have the class Dinero (money in english) which has all properties for the currency in DnD.

class Dinero:
    
    def __init__(self, copper_pieces, silver_pieces, electrum_pieces, gold_pieces, platinum_pieces) -> None:
        self.copper_pieces = copper_pieces
        self.silver_pieces = silver_pieces
        self.electrum_pieces = electrum_pieces
        self.gold_pieces = gold_pieces
        self.platinum_pieces = platinum_pieces
    
    def __str__(self):
        return "Dinero obtenido:\n  Copper: "+str(self.copper_pieces)+"\n  Silver: "+str(self.silver_pieces)+"\n  Electrum: "+str(self.electrum_pieces)+"\n  Gold: "+str(self.gold_pieces)+"\n  Platinum: "+str(self.platinum_pieces)

    def add_gold(self, gold):
        self.gold_pieces += gold

    def agregar_dinero(self, dinero):
        self.copper_pieces += dinero.copper_pieces
        self.silver_pieces += dinero.silver_pieces
        self.electrum_pieces += dinero.electrum_pieces
        self.gold_pieces += dinero.gold_pieces
        self.platinum_pieces += dinero.platinum_pieces

Then I have my class named Mochila (bag in english) which has a list of items and a Dinero class.

import dinero

class Mochila:

    def __init__(self, dinero:dinero.Dinero=dinero.Dinero(0,0,0,0,0), items:list=[]):
        self.items = items
        self.dinero = dinero
    
    def meter_item(self, item):
        self.items.append(item)
    
    def sacar_item(self, item):
        self.items.remove(item)

In my main I set 2 different mochila's and the mochila2 is taking the value of the mochila1's Dinero.

import dinero
import mochila


mochila1 = mochila.Mochila()
mochila2 = mochila.Mochila()

print(mochila2.dinero)

nuevo_dinero = dinero.Dinero(10, 10,200,10,10)

print(mochila2.dinero)

mochila1.dinero.agregar_dinero(nuevo_dinero)

print(mochila2.dinero)

mochila2.dinero.agregar_dinero(mochila1.dinero)
mochila1.dinero = dinero.Dinero(0,0,0,0,0)

Why is this happening and how can I solve this?

1 Answers

Ok, so it looks like both dinero instances are the same, as in if you comment out your str method, you will see they take up the exact same space in memory, so with:

print(mochila2.dinero)
print(mochila1.dinero) 

You get back:

<__main__.Dinero object at 0x0000025D90EC0B08>
<__main__.Dinero object at 0x0000025D90EC0B08>

This is because when you set the default dinero in mochila's constructor, it is using the same default every time, not creating a new instance each time. To fix this, and considering you probably always want a new mochila to start of with 0 money anyway, try jus moving the instantiation of dinero to the constructor:

class Mochila:

    def __init__(self, items: list=[]):
        self.items = items
        self.dinero = Dinero(0, 0, 0, 0, 0)
Related