Question

In a class in Python there are several ways to assign something to a variable.
I always don't know where I should do it, what is the difference in usage and in which scenario should I use a distinct variant.

class Class(object):
    NUMBER = 31415
    foo = 'FOO'

    def __init__(self):
        self.foobar = 'foobar'
Was it helpful?

Solution

Class variables are shared between all instances of a class. That turns out to be pretty self-explanatory. Instance variables however are local to each instantiated object.

Here's an example, first we instantiate a bunch of classes.

In [19]: classes = [Class() for _ in range(5)]

In [20]: classes
Out[20]: 
[<__main__.Class at 0x20bb290>,
 <__main__.Class at 0x20bb2d0>,
 <__main__.Class at 0x20bb310>,
 <__main__.Class at 0x20bb350>,
 <__main__.Class at 0x20bb4d0>]

And then we change the NUMBER-variable of Class

In [21]: Class.NUMBER = "Hah!"

In [22]: print [x.NUMBER for x in classes]
['Hah!', 'Hah!', 'Hah!', 'Hah!', 'Hah!']

However, once you've instantiated the objects, you can change x.NUMBER, and once you do the change is local to that object. I understand this can be quite confusing.

Where as we cannot even touch the foobar-value yet, as it does not exist before the object is instantiated:

In [23]: Class.foobar
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-c680e41ebe07> in <module>()
----> 1 Class.foobar

AttributeError: type object 'Class' has no attribute 'foobar'

This has nothing to do with whether or not the class attributes are upper or lowercase. We can just as well access Class.foo. The point is that everything before the __init__ exists before that class is instantiated to an object. Once that class is instantiated as an object, the object will have the instance attributes, namely obj.foobar.

OTHER TIPS

Class variable will has same value for 2 instances but instance variable will have difference value for each instances.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top