Two instances of class share same vairable in Python












0















So this is very wierd. The code below creates 2 instances of MyClass. One would expect that each has its own copy of the private variable __x which is a dictionary. However, my_class2 updates the value of __x in my_class1 which should not happen in my opinion?



What am I missing?



class MyClass:
__x = dict()

def __init__(self, name, init_value):
self.__x[name] = init_value

def get_value(self):
return self.__x


if __name__ == '__main__':
my_class1 = MyClass("one", 1)
print("my_class1: {}".format(my_class1.get_value()))
my_class2 = MyClass("two", 2)
print("my_class2: {}".format(my_class2.get_value()))
print("my_class1: {}".format(my_class1.get_value()))


The code above leads to the following output:



my_class1: {'one': 1}
my_class2: {'one': 1, 'two': 2}
my_class1: {'one': 1, 'two': 2}









share|improve this question























  • Yes. Of course. Missed that one. Instance variables are defined in functions.

    – Paul
    Nov 23 '18 at 13:04
















0















So this is very wierd. The code below creates 2 instances of MyClass. One would expect that each has its own copy of the private variable __x which is a dictionary. However, my_class2 updates the value of __x in my_class1 which should not happen in my opinion?



What am I missing?



class MyClass:
__x = dict()

def __init__(self, name, init_value):
self.__x[name] = init_value

def get_value(self):
return self.__x


if __name__ == '__main__':
my_class1 = MyClass("one", 1)
print("my_class1: {}".format(my_class1.get_value()))
my_class2 = MyClass("two", 2)
print("my_class2: {}".format(my_class2.get_value()))
print("my_class1: {}".format(my_class1.get_value()))


The code above leads to the following output:



my_class1: {'one': 1}
my_class2: {'one': 1, 'two': 2}
my_class1: {'one': 1, 'two': 2}









share|improve this question























  • Yes. Of course. Missed that one. Instance variables are defined in functions.

    – Paul
    Nov 23 '18 at 13:04














0












0








0








So this is very wierd. The code below creates 2 instances of MyClass. One would expect that each has its own copy of the private variable __x which is a dictionary. However, my_class2 updates the value of __x in my_class1 which should not happen in my opinion?



What am I missing?



class MyClass:
__x = dict()

def __init__(self, name, init_value):
self.__x[name] = init_value

def get_value(self):
return self.__x


if __name__ == '__main__':
my_class1 = MyClass("one", 1)
print("my_class1: {}".format(my_class1.get_value()))
my_class2 = MyClass("two", 2)
print("my_class2: {}".format(my_class2.get_value()))
print("my_class1: {}".format(my_class1.get_value()))


The code above leads to the following output:



my_class1: {'one': 1}
my_class2: {'one': 1, 'two': 2}
my_class1: {'one': 1, 'two': 2}









share|improve this question














So this is very wierd. The code below creates 2 instances of MyClass. One would expect that each has its own copy of the private variable __x which is a dictionary. However, my_class2 updates the value of __x in my_class1 which should not happen in my opinion?



What am I missing?



class MyClass:
__x = dict()

def __init__(self, name, init_value):
self.__x[name] = init_value

def get_value(self):
return self.__x


if __name__ == '__main__':
my_class1 = MyClass("one", 1)
print("my_class1: {}".format(my_class1.get_value()))
my_class2 = MyClass("two", 2)
print("my_class2: {}".format(my_class2.get_value()))
print("my_class1: {}".format(my_class1.get_value()))


The code above leads to the following output:



my_class1: {'one': 1}
my_class2: {'one': 1, 'two': 2}
my_class1: {'one': 1, 'two': 2}






python-3.x class object






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 12:57









PaulPaul

8311




8311













  • Yes. Of course. Missed that one. Instance variables are defined in functions.

    – Paul
    Nov 23 '18 at 13:04



















  • Yes. Of course. Missed that one. Instance variables are defined in functions.

    – Paul
    Nov 23 '18 at 13:04

















Yes. Of course. Missed that one. Instance variables are defined in functions.

– Paul
Nov 23 '18 at 13:04





Yes. Of course. Missed that one. Instance variables are defined in functions.

– Paul
Nov 23 '18 at 13:04












2 Answers
2






active

oldest

votes


















3














You have to declare __x inside the __init__ function, like this:



class MyClass:

def __init__(self, name, init_value):
self.__x = dict()
self.__x[name] = init_value

def get_value(self):
return self.__x





share|improve this answer
























  • Yes, I got that just after I posted. Thanks.

    – Paul
    Nov 23 '18 at 13:05



















1














In your case, the way you were defining __x - it was a class variable - i.e. a variable that is shared by all instances of this class.



You can see this if you run a dir on your instances:



dir(my_class1)
['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']


Note the first entry - it is same above and below.



dir(my_class2) 
['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447164%2ftwo-instances-of-class-share-same-vairable-in-python%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    You have to declare __x inside the __init__ function, like this:



    class MyClass:

    def __init__(self, name, init_value):
    self.__x = dict()
    self.__x[name] = init_value

    def get_value(self):
    return self.__x





    share|improve this answer
























    • Yes, I got that just after I posted. Thanks.

      – Paul
      Nov 23 '18 at 13:05
















    3














    You have to declare __x inside the __init__ function, like this:



    class MyClass:

    def __init__(self, name, init_value):
    self.__x = dict()
    self.__x[name] = init_value

    def get_value(self):
    return self.__x





    share|improve this answer
























    • Yes, I got that just after I posted. Thanks.

      – Paul
      Nov 23 '18 at 13:05














    3












    3








    3







    You have to declare __x inside the __init__ function, like this:



    class MyClass:

    def __init__(self, name, init_value):
    self.__x = dict()
    self.__x[name] = init_value

    def get_value(self):
    return self.__x





    share|improve this answer













    You have to declare __x inside the __init__ function, like this:



    class MyClass:

    def __init__(self, name, init_value):
    self.__x = dict()
    self.__x[name] = init_value

    def get_value(self):
    return self.__x






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 23 '18 at 13:04









    user9849588user9849588

    45317




    45317













    • Yes, I got that just after I posted. Thanks.

      – Paul
      Nov 23 '18 at 13:05



















    • Yes, I got that just after I posted. Thanks.

      – Paul
      Nov 23 '18 at 13:05

















    Yes, I got that just after I posted. Thanks.

    – Paul
    Nov 23 '18 at 13:05





    Yes, I got that just after I posted. Thanks.

    – Paul
    Nov 23 '18 at 13:05













    1














    In your case, the way you were defining __x - it was a class variable - i.e. a variable that is shared by all instances of this class.



    You can see this if you run a dir on your instances:



    dir(my_class1)
    ['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']


    Note the first entry - it is same above and below.



    dir(my_class2) 
    ['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']





    share|improve this answer




























      1














      In your case, the way you were defining __x - it was a class variable - i.e. a variable that is shared by all instances of this class.



      You can see this if you run a dir on your instances:



      dir(my_class1)
      ['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']


      Note the first entry - it is same above and below.



      dir(my_class2) 
      ['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']





      share|improve this answer


























        1












        1








        1







        In your case, the way you were defining __x - it was a class variable - i.e. a variable that is shared by all instances of this class.



        You can see this if you run a dir on your instances:



        dir(my_class1)
        ['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']


        Note the first entry - it is same above and below.



        dir(my_class2) 
        ['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']





        share|improve this answer













        In your case, the way you were defining __x - it was a class variable - i.e. a variable that is shared by all instances of this class.



        You can see this if you run a dir on your instances:



        dir(my_class1)
        ['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']


        Note the first entry - it is same above and below.



        dir(my_class2) 
        ['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 13:16









        MortzMortz

        669418




        669418






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447164%2ftwo-instances-of-class-share-same-vairable-in-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'