Two instances of class share same vairable in Python
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
add a comment |
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
Yes. Of course. Missed that one. Instance variables are defined in functions.
– Paul
Nov 23 '18 at 13:04
add a comment |
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
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
python-3.x class object
asked Nov 23 '18 at 12:57
PaulPaul
7611
7611
Yes. Of course. Missed that one. Instance variables are defined in functions.
– Paul
Nov 23 '18 at 13:04
add a comment |
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
add a comment |
2 Answers
2
active
oldest
votes
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
Yes, I got that just after I posted. Thanks.
– Paul
Nov 23 '18 at 13:05
add a comment |
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']
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
Yes, I got that just after I posted. Thanks.
– Paul
Nov 23 '18 at 13:05
add a comment |
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
Yes, I got that just after I posted. Thanks.
– Paul
Nov 23 '18 at 13:05
add a comment |
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
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
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
add a comment |
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
add a comment |
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']
add a comment |
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']
add a comment |
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']
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']
answered Nov 23 '18 at 13:16
MortzMortz
628417
628417
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
Yes. Of course. Missed that one. Instance variables are defined in functions.
– Paul
Nov 23 '18 at 13:04