I wrote a longer one while you were typing thatMilkymalk wrote:I'm fine with simplyfied explanations
Milkymalk wrote:But another question:
Why does this change the sp outside the function:and this does not change amount outside the function?Code: Select all
class Test: def cast_spell(self, sp): effectbuffer = sp.effects while len(effectbuffer) > 0: currenteffect = effectbuffer.pop() [...stuff...]
Code: Select all
def change_mana(self, target, change_to, amount, position): if position == 1: step = 1 elif position == 2: step = -1 deletemana = [ ] for i in range(15): deletemana.append(False) for i in range(15): if amount > 0 and (self.balls_color[7-(7-i)*step] == target or target == -1) and not self.ballselected[7-(7-i)*step]: if change_to == -3: deletemana[7-(7-i)*step] = True amount -= 1
Code: Select all
effectbuffer = sp.effects
In change_mana you're reassigning "amount" to a variable on change_mana scope, global (or whatever outer scope you're using) has no way of knowing that, so:
Code: Select all
amount -= 1
Code: Select all
amount = amount - 1
Reference variable "amount" on local scope to be whatever the supplied attribute "amount" referenced to on the outer scope and subtract one from it. In all consecutive loops, newly created local variable "amount" is used.
Behavior is exactly the same with lists (because .pop(), .append() do not reassign anything):
Code: Select all
def func(l):
for i in xrange(10, 100):
l = l + [i]
a = range(10)
func(a)
while:
Code: Select all
def func(l):
for i in xrange(10, 100):
l.append(i)
a = range(10)
func(a)