The simplest way:

In [12]: class MyClass(object):
...:         attr = 'attr value'

In [15]: MyClass.attr
Out[15]: 'attr value'

You can use __dict__ attribute also:

__dict__ is the dictionary containing the class's namespace.

In [15]: MyClass.__dict__.get('attr', None)
Out[15]: 'attr value'

Use staticmethod decorator if you need to use a method:

In [12]: class MyClass(object):
...:         @staticmethod
...:         def the_static_method(x):
...:             print(x)


In [15]: MyClass.the_static_method(2)
Out[15]: 2
Answer from SayPy on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
In our example, the call x.f() ... object before the first argument. In general, methods work as follows. When a non-data attribute of an instance is referenced, the instance’s class is searched....
Discussions

python - Calling class attribute without creating an instance to that class - Stack Overflow
I would like to initialize a class, then call an attribute which was set during the initialization, but without creating another instance. As a test example: class t1: def __init__(self, skipI... More on stackoverflow.com
🌐 stackoverflow.com
Checking my understanding of class attributes vs. instance attributes
Yes, your understanding seems to be correct. Regarding having a immutable data, you would likely need to use a pattern like frozendict (if your data is still stored as a dict) otherwise just use a metaclass to override the getattribute and setattributes of the "data" class. More on reddit.com
🌐 r/learnpython
8
32
December 26, 2022
python - New instance of class with a non-None class attribute? - Stack Overflow
I have a Python class that has a class attribute set to something other than None. When creating a new instance, the changes made to that attribute perpetuates through all instances. Here's some c... More on stackoverflow.com
🌐 stackoverflow.com
python - What is the difference between class and instance attributes? - Stack Overflow
Is there any meaningful distinction between: class A(object): foo = 5 # some default value vs. class B(object): def __init__(self, foo=5): self.foo = foo If you're creating a lo... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What happens if both instance attribute and class attribute are defined?

In that case, the instance namespace takes precedence over the class namespace. If there is an attribute with the same name in both, the instance namespace will be checked first and its value returned.

🌐
toptal.com
toptal.com › developers › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: An Overly Thorough Guide | Toptal®
Python class method versus instance method: What’s the difference?

In Python, a class method is a method that is invoked with the class as the context. This is often called a static method in other programming languages. An instance method, on the other hand, is invoked with an instance as the context.

🌐
toptal.com
toptal.com › developers › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: An Overly Thorough Guide | Toptal®
What is a Python namespace?

A Python namespace is a mapping from names to objects, with the property that there is zero relation between names in different namespaces. Namespaces are usually implemented as Python dictionaries, although this is abstracted away.

🌐
toptal.com
toptal.com › developers › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: An Overly Thorough Guide | Toptal®
🌐
Turing
turing.com › kb › introduction-to-python-class-attributes
A Guide to Python Class Attributes and Class Methods
Class attributes can be used to create singleton objects, which are objects that are created only once and can be shared among multiple parts of your code. Singletons are commonly used for shared resources, such as database connections, caches, and other objects that should only exist once in a system. To create a singleton in Python, you can create a class with a class attribute that holds the singleton object: class Database: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
🌐
Built In
builtin.com › software-engineering-perspectives › python-attributes
Python Attributes: Class vs. Instance | Built In
... Summary: Python class attributes are shared across all instances, while instance attributes are unique to each object. Attribute lookup starts in the instance’s namespace, then checks the class.
🌐
GitHub
hplgit.github.io › primer.html › doc › pub › class › ._class-solarized006.html
Introduction to classes in Python
Since this argument is missing inside the method, we can never access non-static attributes since these always must be prefixed by an instance (i.e., self). However, we can access static attributes, prefixed by the classname. If desired, we can make an instance and call write through that instance ...
🌐
Python Course
python-course.eu › oop › class-instance-attributes.php
2. Class vs. Instance Attributes | OOP | python-course.eu
March 22, 2024 - As we mentioned before, we can access a class attribute via instance or via the class name. You can see in the following that we don't need an instance:
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › checking my understanding of class attributes vs. instance attributes
r/learnpython on Reddit: Checking my understanding of class attributes vs. instance attributes
December 26, 2022 -

I've got a relatively large dictionary that a class needs to work with, but I only need one copy of the dictionary; I don't need to create a new copy for every instance of the object.

As I understand it, what I can do is this:

class myClass( object ):

theDictionary = { ... }

def __init__(self):

#not relevant, just showing that it's separate from the constructor

And (again, as I understand it) this will result in ONE dictionary that is used by ALL instances-- with the caveat that it is both mutable ( any changes made by one instance will affect all instances ) and not remotely threadsafe.

I was originally thinking of this as memory conservation, but I had an epiphany while I was typing the above. If I've got this correct, one could create a class that is nothing but attributes (and, if needed, thread-safe methods to access said attributes), and make any class that needs to read or modify the data stored in those attributes a child of that class, creating a shared data environment for the entire application without constantly have to pass objects around between classes and/or instances.

I'm really hoping I've got this correct.

As a side note: Is there a way to make a class attribute that's NOT mutable? It's not relevant to the project I'm working on, but I can see situations where I would want a class to operate from a set of data that I didn't want to duplicate for every instance, but didn't want to alter.

EDIT: In case you come across this while googling, this is correct... but incomplete.

There are two ways to access a class variable (in the above case self.theDictionary and myClass.theDictionary). They are interchangeable unless you declare self.theDictionary as an instance variable.

In the case of a dictionary, making a change to it wouldn't be a problem, because when you say (for example) self.theDictionary['word']='meaning', you're not redeclaring self.theDictionary.

But if you wanted to replace the dictionary altogether, you'd want to use myClass.theDictionary = { ... }. The reason for this is that if you say self.theDictionary = { ... }, you're not overwriting the class attribute, you're creating an instance attribute.

Once you create an instance attribute, python will see self.theDictionary as the new dictionary, and you will only be able to access the old one with myClass.theDictionary.

🌐
Toptal
toptal.com › developers › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: An Overly Thorough Guide | Toptal®
January 16, 2026 - It’s preferable to have something that is correct by construction. My personal solution: If you’re just using a class variable to assign a default value to a would-be Python instance variable, don’t use mutable values. In this case, every instance of Service was going to override Service.data with its own instance attribute eventually, so using an empty list as the default led to a tiny bug that was easily overlooked.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-attributes-class-vs-instance-explained
Python Attributes: Class Vs. Instance Explained - GeeksforGeeks
July 23, 2025 - In object-oriented programming (OOP), a class is a blueprint for creating objects, and class attributes are variables that are associated with a class rather than with instances (objects) of that class.
Top answer
1 of 4
8

Yes, this is how it is supposed to work.

If a and b belong to the instance of Foo, then the correct way to do this is:

class Foo(object):
   def __init__(self):
     self.a = []
     self.b = 2

The following makes a and b belong to the class itself, so all instances share the same variables:

class Foo(object):
   a = []
   b = 2

When you mix the two methods -- as you did in your second example -- this doesn't add anything useful, and just causes confusion.

One caveat worth mentioning is that when you do the following in your first example:

foo.b = 5

you are not changing Foo.b, you are adding a brand new attribute to foo that "shadows" Foo.b. When you do this, neither bar.b nor Foo.b change. If you subsequently do del foo.b, that'll delete that attribute and foo.b will once again refer to Foo.b.

2 of 4
1

Yes, that's exactly what you should expect. When you define a variable on the class, then those attributes are attached to the class, not the instance. You might not always notice that when you assign to an attribute on an instance, the instance picks up the new value, masking the class attribute. Methods that modify in place, like list.append won't give the instance a new attribute, since they just modify existing object, which happens to be an attribute of the class.

Any time every instance of a class should have its own, unique value for an attribute, you should usually set that in the __init__ method, to be sure that it's different for every instance.

only when a class has an attribute that has a sensible default value, and that value is of an immutable type (that cannot be modified in place), such as int or str, should you set attributes on the class.

🌐
freeCodeCamp
freecodecamp.org › news › python-attributes-class-and-instance-attribute-examples
Python Attributes – Class and Instance Attribute Examples
April 12, 2022 - You can call it whatever you want – by convention, self is mostly used. The school variable acts as a class attribute while name and course are instance attributes. Let's break the example above down to explain instance attributes. Student1 = Student("Jane", "JavaScript") Student2 = Student("John", "Python") print(Student1.name) # Jane print(Student2.name) # John
Top answer
1 of 5
181

There is a significant semantic difference (beyond performance considerations):

  • when the attribute is defined on the instance (which is what we usually do), there can be multiple objects referred to. Each gets a totally separate version of that attribute.
  • when the attribute is defined on the class, there is only one underlying object referred to, so if operations on different instances of that class both attempt to set/(append/extend/insert/etc.) the attribute, then:
    • if the attribute is a builtin type (like int, float, boolean, string), operations on one object will overwrite (clobber) the value
    • if the attribute is a mutable type (like a list or a dict), we will get unwanted leakage.

For example:

Copy>>> class A: foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[5]
>>> class A:
...  def __init__(self): self.foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo    
[]
2 of 5
48

Here is a very good post, and summary it as below.

Copyclass Bar(object):
    ## No need for dot syntax
    class_var = 1

    def __init__(self, i_var):
        self.i_var = i_var

## Need dot syntax as we've left scope of class namespace
Bar.class_var
## 1
foo = Bar(2)

## Finds i_var in foo's instance namespace
foo.i_var
## 2

## Doesn't find class_var in instance namespace…
## So look's in class namespace (Bar.__dict__)
foo.class_var
## 1

And in visual form

Class attribute assignment

  • If a class attribute is set by accessing the class, it will override the value for all instances

    Copy  foo = Bar(2)
      foo.class_var
      ## 1
      Bar.class_var = 2
      foo.class_var
      ## 2
    
  • If a class variable is set by accessing an instance, it will override the value only for that instance. This essentially overrides the class variable and turns it into an instance variable available, intuitively, only for that instance.

    Copy  foo = Bar(2)
      foo.class_var
      ## 1
      foo.class_var = 2
      foo.class_var
      ## 2
      Bar.class_var
      ## 1
    

When would you use class attribute?

  • Storing constants. As class attributes can be accessed as attributes of the class itself, it’s often nice to use them for storing Class-wide, Class-specific constants

    Copy  class Circle(object):
           pi = 3.14159
    
           def __init__(self, radius):
                self.radius = radius   
          def area(self):
               return Circle.pi * self.radius * self.radius
    
      Circle.pi
      ## 3.14159
      c = Circle(10)
      c.pi
      ## 3.14159
      c.area()
      ## 314.159
    
  • Defining default values. As a trivial example, we might create a bounded list (i.e., a list that can only hold a certain number of elements or fewer) and choose to have a default cap of 10 items

    Copy  class MyClass(object):
          limit = 10
    
          def __init__(self):
              self.data = []
          def item(self, i):
              return self.data[i]
    
          def add(self, e):
              if len(self.data) >= self.limit:
                  raise Exception("Too many elements")
              self.data.append(e)
    
       MyClass.limit
       ## 10
    
🌐
Duke
fintechpython.pages.oit.duke.edu › jupyternotebooks › 1-Core Python › answers › rq-25-answers.html
Core Python / Classes and Objects — Programming for Financial Technology
In Python, instance attributes are defined within the __init__ method of a class. These attributes are specific to each instance (object) of the class and can have different values for different instances. There are two ways to define instance attributes: ... Instance attributes are typically initialized inside the __init__ method. The self parameter is used to refer to the instance being created (technically, it is the position that matters, self is the expected convention used.), and instance attributes are assigned values using the dot notation (self.attribute_name = value).
🌐
Real Python
realpython.com › lessons › class-and-instance-attributes
Class and Instance Attributes (Video) – Real Python
When we instantiate the Dog class, we’ll need to pass in values for name and age, and then this function will assign the new object those values. self is a very special keyword, and the fact that we have to include it in our parameters is one of those little Python quirks. 04:17 We don’t pass a value in for self when we create the object. Instead, self is used to refer to the current object being created during instantiation. 04:26 So when we say self.age = age, we’re saying, “Take the value of age we pass in, and assign that to the new object’s .age attribute”—and the same goes for name.
Published   March 22, 2019
🌐
Quora
quora.com › When-is-it-best-to-use-class-attributes-instead-of-instance-attributes-in-Python
When is it best to use class attributes instead of instance attributes in Python? - Quora
Answer (1 of 3): Well, they’re different things, so it’s best to use the one that’s the one you want. In general, class attributes are good for: * A constant that should be the same for every instance of the class—especially if you might need to override for every instance of a subclass.
🌐
TutorialsPoint
tutorialspoint.com › class-and-instance-attributes-in-python
Class & Instance Attributes in Python
Simply putting ?pass' means ClassB does not have its own attributes it simply points to its parent class. And secondly, we hardcoded the class name due to our temptation. Also, calling this function will require an object to be created first as it expects a ?self' reference. Instead we can use something called a "Class Method", which has a decorator of the same name. Here's how it should look ? ... It basically says that we want to change the attribute of that specific class only from which it was called.
🌐
Bruceeckel
bruceeckel.com › 2022 › 05 › 11 › misunderstanding-python-class-attributes
Misunderstanding Python Class Attributes
May 11, 2022 - Unlike C++ and Java, Python allows instance variables to shadow (have the same name as) class attributes. This feature gets significant use in libraries that simplify configuration by using class attributes to automatically generate constructors and other methods.
🌐
Python.org
discuss.python.org › python help
Should I still use an instance attribute in this scenario? - Python Help - Discussions on Python.org
September 20, 2023 - I’ve got a question that might ... Some preamble: when creating a class, attributes that should be inherited by every instance of the class are defined outside of the __init__ method - so called class attributes....