类变量 vs 实例变量 --Python [英] class variable vs instance variable --Python

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

问题描述

我在下面的例子中尝试了这个,需要一些说明.在这两种情况下,我都可以在测试函数中访问类变量和实例.

I tried this below example and need some clarification..In both the cases, I'm able to access the class variable and instance in test function.

那么,假设我必须定义一个需要在所有函数中使用的文字,哪个是定义..self 变量或类变量的更好方法?

So, assume if I have to define a literal that needs to be used across all function, which would be the better way to define..self variable or class variable?

代码.py

class testclass:
    classvar = 'its classvariable LITERAL'
    def __init__(self,x,y):
        self.z = x
        self.classvar = 'its initvariable LITERAL'

        self.test()

    def test(self):
        print('class var',testclass.classvar)
        print('instance var',self.classvar)

if __name__ == '__main__':
    x = testclass(2,3)

推荐答案

类变量非常适合所有实例使用的常量"(所有方法都是技术上的).您可以使用模块全局变量,但使用类变量可以使其与类更清晰地关联.

Class variables are quite good for "constants" used by all the instances (that's all methods are technically). You could use module globals, but using a class variable makes it more clearly associated with the class.

通常也有实际更改的类变量的用途,但通常最好远离它们,原因与避免通过更改全局变量使程序的不同部分进行通信的原因相同.

There are often uses for class variables that you actually change, too, but it's usually best to stay away from them for the same reason you stay away from having different parts of your program communicate by altering global variables.

实例变量用于实际属于实例的数据.对于每个特定实例,它们可能不同,并且它们经常在单个特定实例的生命周期内发生变化.最好将实例变量用于在概念上属于实例的数据,即使在您的程序中您碰巧只有一个实例,或者您有几个实例在实践中始终具有相同的值.

Instance variables are for data that is actually part of the instance. They could be different for each particular instance, and they often change over the lifetime of a single particular instance. It's best to use instance variables for data that is conceptually part of an instance, even if in your program you happen to only have one instance, or you have a few instances that in practice always have the same value.

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

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