Home  >  Q&A  >  body text

实例化 - Python怎么避免不同的实例之间共享变量?

PHP中文网PHP中文网2716 days ago382

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-17 17:03:24

    What you declare is 类变量 not a member variable, which means your value is bound to the type, not the instance.

    Try this

    def A(object):
        def __init__():
            self.value = [ ]
        def append(v):
            self.value.append(v)

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:03:24

    class MyClass():
        def __init__(self):
            self.value=[]
        def append(self,value):
               self.value.append(value)
        def get(self):
               return self.value
    instance_a=MyClass()
    instance_b=MyClass()
    instance_a.append(100)
    print instance_b.get()
    print instance_a.get()

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:03:24

    The questioner can take a look at this: https://www.zhihu.com/question/25874136
    Explanation on static variables and instance variables.
    As for how to operate, the above two answers have been clearly listed.

    实例变量是要在`__init__(self)`中定义的变量。如果没有定义变量,那就会搜索scope上同名变量。

    reply
    0
  • Cancelreply