实例化 - Python怎么避免不同的实例之间共享变量?
PHP中文网
PHP中文网 2017-04-17 17:01:24
0
3
380
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
PHPzhong

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)
Ty80
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()
洪涛

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上同名变量。
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!