Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class variable vs instance variable --Python

Tags:

python

I tried this example code:

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)

I need some clarification. In both cases, I'm able to access the class attribute and instance in the test method.

So, suppose if I have to define a literal that needs to be used across all function, which would be the better way to define it: an instance attribute or a class attribute?

like image 427
user1050619 Avatar asked Sep 30 '12 01:09

user1050619


1 Answers

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
like image 104
Juan Fco. Roco Avatar answered Oct 20 '22 19:10

Juan Fco. Roco