类变量Vs.python中的实例变量的int值 [英] Class variable Vs. Instance variable in python for int value

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

问题描述

我是python的新手,我不确定这是如何工作的.代码如下:

I am new to python and i am not sure how this is working. Code is as below:

class test():
    d=0
    def __init__(self):
       self.d=self.d+1;

D=test()
print D.d
D1=test()
print D1.d
D2=test()
print D2.d

输出为

1,1,1  # This should not be

现在使用这个:

class test():
    d=[]
    def __init__(self):
       self.d.apend("1");

 D=test()
 print D.d
 D1=test()
 print D1.d
 D2=test()
 print D2.d

结果是(应该是)

['1']
['1', '1']
['1', '1', '1']

因此,我不确定在处理列表时为什么不将整数值不视为类变量.

So i am not sure why integer value is not being treated as class variable while list is being treated.

推荐答案

如果要修改类变量,请执行以下操作:

If you want to modify a class variable, do:

class test(object):
    d=0
    def __init__(self):
       type(self).d=self.d+1;

D=test()
print D.d
D1=test()
print D1.d
D2=test()
print D2.d

您不需要分配右侧的 type ,因为这样您就永远不会创建实例变量 d .请注意,为此需要新样式的类.

You don't need the type on the right hand side of the assignment, because this way you never create an instance variable d. Note that new-style classes are necessary to this.

type 是一个函数(实际上是一个可调用的-它也是一个类;但是暂时不用担心),它返回其参数的类.因此, type(self)返回 self 的类.类是Python中的一流对象.

type is a function (actually a callable - it is also a class; but don't worry about that for now) which returns the class of its argument. So, type(self) returns the class of self. Classes are first class objects in Python.

此处演示: http://ideone.com/JdNpiV

更新:一种替代方法是使用 classmethod .

Update: An alternative would be to use a classmethod.

这篇关于类变量Vs.python中的实例变量的int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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