类的两个实例在Python中共享相同的变量 [英] Two instances of class share same vairable in Python

查看:368
本文介绍了类的两个实例在Python中共享相同的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这很奇怪。下面的代码创建2个MyClass实例。可以期望每个人都有自己的私有变量__x的副本,后者是一本字典。但是,my_class2更新了my_class1中的__x值,我认为这不应该发生?

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?

我缺少了什么?

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}


推荐答案

您必须在__init__函数内部声明__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

这篇关于类的两个实例在Python中共享相同的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆