How should I choose between using instance vs. class attributes?

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

Leave a Comment