0

I want to add one element to list in one variable with Data class. Why when I append condition class to a data list class it is added to all other variables as well? What I'm doing wrong here? Whole code below:

from copy import copy


class Condition:
    def __init__(self, name, time=2):
        self.name = name
        self.time = time


class Data:
    def __init__(self, name, state=[]):
        self.name = name
        self.state = state

pc = Data("pc1")
pc2 = Data("pc2")
dps_buff = Condition('data')

pc.state.append(copy(dps_buff))

counter = 1

while counter < 10:
    for condition in pc.state:
        if condition.time > 0:
            condition.time -= 1
            print pc.state, 1
            print pc2.state, 2

        elif condition.time == 0:
            print 'empty', condition.time
            pc.state.remove(condition)

    counter += 1

print pc.state
print pc2.state

Output:

C:\Python27\python.exe "D:/Python/Tests/test.py"
[<__main__.Condition instance at 0x0000000002CAF408>] 1
[<__main__.Condition instance at 0x0000000002CAF408>] 2
[<__main__.Condition instance at 0x0000000002CAF408>] 1
[<__main__.Condition instance at 0x0000000002CAF408>] 2
empty 0
[]
[]

Intended output:

C:\Python27\python.exe "D:/Python/Tests/test.py"
[<__main__.Condition instance at 0x0000000002CAF408>] 1
[] 2
[<__main__.Condition instance at 0x0000000002CAF408>] 1
[] 2
empty 0
[]
[]
Hsin
  • 307
  • 5
  • 15
  • `def __init__(self, name, hp, power, state=[]):`: state is a default mutable argument. Don't do this. – Jean-François Fabre Jul 05 '17 at 18:56
  • I appreciate answer but when I look at link provided I see a lot of theory but not the answer. I'm beginner at python and I can't find answer to my question. – Hsin Jul 05 '17 at 19:07
  • it means: the reference of the empty list passed as default parameter `state` is used for every instance: modifying one modifies all the others. – Jean-François Fabre Jul 05 '17 at 19:08
  • For anyone else having this problem I found answer inside another link: http://effbot.org/zone/default-values.htm / instead of state=[] i need to define list below like / self.state = [] – Hsin Jul 05 '17 at 19:10
  • please post the link, we'll add it as a second original question to the duplicate (I think there are a lot of duplicates, this is a common mistake) – Jean-François Fabre Jul 05 '17 at 19:11
  • Thanks for answers. I understand that this is probably obvious and just stupid mistake for you but at my current level I don't understand most of detailed theory provided in stackoverflow link you gave me. – Hsin Jul 05 '17 at 19:15

0 Answers0