类变量是共享的所有实例在python? [英] class variables is shared across all instances in python?

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

问题描述

我在一个星期前开始在python编码,这是我的错误,我开始编码使用oops,类和对象很快。我假设我的C ++熟练程度会帮助....我有以下代码位:

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


$ b b

这里令我感到意外的是,var和list是一个全局变量,它在所有实例之间共享,似乎....我想到的是在所有实例之间是不同的......它花了我一半一天来弄清楚....它并不使得甚至没有意义,一个变量只能通过一个类对象访问,但是在所有实例共享...只是好奇,是有一个原因背后it

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 只要您通过 instance.var self.var 访问它。然而,使用列表,你的语句做的是当类被评估时,一个列表实例被创建并绑定到类dict,因此所有实例将有相同的列表。每当你设置 instance.list = somethingelse self.list = somethingelse ,它应该获得一个实例级值。

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.

示例时间:

>>> 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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