2

I cant really show my code but i can explain the problem. Im using python 2.7 and I created 2 instances of a class I wrote. For some reason when i change the field of lets say email in one instance, the same field will change to the same value on the other instance. Does anyone know of such a problem or what did I do wrong? if more explanation is needed please tell me

example:

class EX:   
    def __init__(self, _email = " "):
        set_email(_email)

    def get_email(self):
        return self._email

    def set_email(self, email):
        self._email = email


if __name__ == '__main__':
    ex1 = EX()
    ex2 = EX()
    ex1.set_email("user@user.com")
    print ex1.get_email() #both print the same "user@user.com"
    print ex2.get_email()
Yarden
  • 496
  • 1
  • 5
  • 16
  • 1
    if you can't post your own code at least take the time to post a minimal work example that illustrates what you are seeing :http://sscce.org/ – dm03514 May 28 '14 at 14:37
  • `NameError: name 'set_email' is not defined` at line 3 And even if change it to self.set_email, the output is only the first email. – Anton Melnikov May 28 '14 at 15:38
  • 1
    if email is not a string but a mutable object as an array you initialize with `def __init__(self, _email = []):` you could have similar error the point is default arguments should not be mutable object and you should use `def __init__(self, _email = None): if _email is None: _email = []` – Xavier Combelle May 28 '14 at 15:47
  • Thank you, i tried your answer and it worked :) – Yarden May 28 '14 at 17:05

2 Answers2

0

You should use self variables.

Here is a simplified example:

class A:
    def __init__(self, val):
        self.value = val

a = A(5)
b = A(6)
a.value = 9

>>> print a.value
9
>>> print b.value
6
sshashank124
  • 31,495
  • 9
  • 67
  • 76
0

You really have to show an example of your code, maybe a simplified example of how do you create and use classes and instances.

I guess you've defined class attributes instead of instance attributes:

class A(object):
    class_attr = 'eh'

    def __init__():
        self.instance_attr = 42

Class attributes will change across of all it's instances if you change them in one instance.

UPDATE: I've corrected your example:

class EX:
    def __init__(self, _email = " "):
        self._email = _email
        self.set_email(_email)

    def get_email(self):
        return self._email

    def set_email(self, email):
        self._email = email


if __name__ == '__main__':
    ex1 = EX()
    ex2 = EX()
    ex1.set_email("user@user.com")
    print ex1.get_email() # this prints
    print ex2.get_email() # this doesn't
Anton Melnikov
  • 1,048
  • 7
  • 21