Class variables


this is an annoying behavior, I’m having a lot of bug because my class variables change even if I didn’t assign a value to them directly.

for instance,

class character:
   def __init__(self): = 3
      self.magic =
      self.jump = self.magic

   def setJump(self, value):
      self.jump = value

   def getLife(self):

if I insert setJump(5), life and magic store 5 too, it seems that was created only one variable. = self.magic = self.jump = 3

this solved my problem and seems to create 3 different variables.

But now every time I assign a class variable to a variable and I change the value of the variable, the class variable changes as well

myVariable = character.getLife()
myVariable = 10

this prints:
myVariable = 10 = 10

myVariable = character.getLife() + 0
myVariable += 10

it is the only way that works perfectly
myVariable = 13 = 3

I will get crazy, why python is tricking me? :imp: :angry:
please help me :confused:

I’m no Python programmer, but

def getLife(self):
return value

shouln’t that be return ??

he had value defined on top. So the getLife returns the top level socope value, same value he is setting.

Argh… strange language… I will not enter the dangerous world of answering Python questions any more :slight_smile:

No, you gave the correct answer. getLife() should indeed be returning, not value. The fact that it was returning value is exactly why it was behaving strangely.


Thanks, I feel much better now :laughing:

my mistake,
it indeed returns :stuck_out_tongue:

is this solved now or are you still confused about class- and instance attributes?

I don’t know whether your problem is something like this: … sld016.htm

sometimes python language kinda strange on assigning object, beware its says :slight_smile:

nemesis#13 I am still a bit confused :confused:

bear_form that is exactly what is happening,
I want to create, for instance, a new int object by referencing
x = y
and not make x reference the object y references, how can I avoid this?

you should be aware that python handles int and float a bit differently to lists.

>>> a = b = 1
>>> a += 1
>>> a, b
(2, 1)
>>> a = b = [1]
>>> a += [1]
>>> a, b
([1, 1], [1, 1])

so variables to lists are pointers.

to copy a list use

a = b[:]

edit: oh i didnt read the link posted by bear_form posted… so this may be bogus

so what exactly is the problem?

from the first post i guess it’s confusion about class- and instance variables. this little website might help you in this case: … 12007.html