相关疑难解决方法(0)

类变量vs实例变量--Python

我在下面的例子中尝试了这个并且需要一些澄清.在这两种情况下,我都能够访问测试函数中的类变量和实例.

所以,假设我必须定义一个需要在所有函数中使用的文字,这将是更好的定义自身变量或类变量的方法吗?

code.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)
Run Code Online (Sandbox Code Playgroud)

python

4
推荐指数
3
解决办法
8991
查看次数

标签 统计

python ×1