Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

class variable vs instance variable --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.

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?

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know this is an old one.. but I found this in an old presentation made by Guido van Rossum in 1999 ( http://legacy.python.org/doc/essays/ppt/acm-ws/sld001.htm ) and I think it explains the topic beautifully:

Instance variable rules

On use via instance (self.x), search order:

  • (1) instance, (2) class, (3) base classes
  • this also works for method lookup

On assigment via instance (self.x = ...):

  • always makes an instance variable
  • Class variables "default" for instance variables

But...!

  • mutable class variable: one copy shared by all
  • mutable instance variable: each instance its own

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...