类变量在python中的所有实例之间共享

类变量在python中的所有实例之间共享

本文介绍了类变量在python中的所有实例之间共享?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一周前开始用 python 编码,这是我的错误,我很快就开始使用 oops、类和对象进行编码.我认为我的 C++ 熟练程度会有所帮助....我被以下代码咬了一口

A 类:无功=0列表=[]def __init__(self):经过

令我惊讶的是,var 和 list 是一种全局变量,它似乎在所有实例之间共享......我认为它在所有实例中都不同......我花了半天时间弄清楚......它没有任何意义,一个变量只能被一个类对象访问,但在所有实例之间共享.......只是好奇,背后有什么原因?????

解决方案

var 绝对不应该共享,只要你通过 instance.var 访问它>self.var.但是,对于列表,您的语句所做的是在对类进行评估时,创建一个列表实例并将其绑定到类 dict,因此所有实例都将具有相同的列表.每当您设置 instance.list = somethingelse 时.self.list = somethingelse,它应该得到一个实例级别的值.

示例时间:

>>>A类():... 变量 = 0...列表= []...>>>a = A()>>>b = A()>>>无功0>>>一个列表[]>>>b.var0>>>b.列表[]>>>a.var = 1>>>b.var0>>>a.list.append('你好')>>>b.列表['你好']>>>b.list = ['newlist']>>>一个列表['你好']>>>b.列表['新名单']

I started coding in python a week ago, it is my mistake i started coding using oops,classes and objects that soon. I assumed my C++ proficiency will help.... I got bit by the following code

class A:
     var=0
     list=[]
     def __init__(self):
            pass

Here to my surprise, var and list are kinda global variable, it is shared across all instances it seems.... What I thought was it was different across all the instances..... It took me half a day to figure out that.... It does not make even slightest sense, that a variable can be accessed by a class object only, but is shared across all instances....... Just Curious, is there a reason behind it?????

解决方案

var should definitely not be shared as long as you access it by instance.var or self.var. With the list however, what your statement does is when the class gets evaluated, one list instance is created and bound to the class dict, hence all instances will have the same list. Whenever you set instance.list = somethingelse resp. self.list = somethingelse, it should get an instance level value.

Example time:

>>> class A():
...     var = 0
...     list = []
...
>>> a = A()
>>> b = A()
>>> a.var
0
>>> a.list
[]
>>> b.var
0
>>> b.list
[]
>>> a.var = 1
>>> b.var
0
>>> a.list.append('hello')
>>> b.list
['hello']
>>> b.list = ['newlist']
>>> a.list
['hello']
>>> b.list
['newlist']

这篇关于类变量在python中的所有实例之间共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:35