Class variables vs Class attributes

I have a few questions about class variables and class attributes.

What are the differences between them?
When should they be used?
Can they be used interchangeably?

Thank you in advance

Hi, there!

I need some clarification before providing an answer. Which language are you requesting help in?

class Foo:
    foo = "Class variable"
    def __init__(self, bar): = bar
>>> foo = Foo('instance variable')
'Class variable'
'instance variable'
'Class variable'
Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
AttributeError: type object 'Foo' has no attribute 'bar'


Something else to add to the kit: We cannot mutate the class variable with an instance. In that case we assign the new value to a newly created attribute that shadows the class variable.

>>> = "class to instance variable"
'Class variable'
'class to instance variable'

Note that foo now has its own ‘foo’ attribute and can no longer access the class variable, except by direct (Parent class) access.

>>> dir(foo)
[..., 'bar', 'foo']

Hey there, sorry this is coming 6 hours late. The language is Python

1 Like


The situations that present with a need for class variables are for convenience and maybe even preference, but we would like to think there is a good reason for it.

Let’s try to think up a good reason. Hmmm. Oh! What about ID numbers?

>>> class Member:
...     id = 0
...     def get_id():
... += 1
...         return
...     def __init__(self, name):
... = name
... = Member.get_id()
>>> a = Member('john')
>>> b = Member('jane')
>>> a = Member('jon')
>>> b = Member('jan')

Notice when we replace a and b they have new ids.


Python was assumed because it is in a Python category and the question was relatable.


This is very helpful, thank you so much.

1 Like

class Foo:
foo = “Class variable”
def init(self, bar): = bar

I understand these lines. The class Foo has a class variable called foo. We then add a constructor to define the attributes of class Foo as self, and bar.

The following line is a bit confusing, and I’d appreciate some light shed on it.

foo = Foo(‘instance variable’)

I understand that this is an instance. What I don’t understand though is why Foo(self, bar) is being replaced with Foo('instance variable).

There is more I don’t understand. But If you will indulge me, could we go step by step, please?

Thank you so very much

self is not an attribute. It is the instance object. That is what, in that setting has the attribute, bar. When we instantiate a new object,

foo = Foo('instance variable')

the argument we have given is the value that will be assigned to the bar attribute. We’re not replacing anything.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.