Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

Answer from user44484 on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
When the method object is called ... variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:...
🌐
PYnative
pynative.com › home › python › python object-oriented programming (oop) › python class variables
Python Class Variables With Examples – PYnative
September 8, 2023 - Class Variables: A class variable is a variable that is declared inside of a Class but outside of any instance method or __init__() method. ... Instance variable vs. class variables ...
Discussions

Class variables
Hi, I am confused about class variable and instance variable in below example: class Classy: varia = 2 def method(self): print(self.varia, self.var) obj = Classy() obj.var = 3 obj.method() Don’t we access class variables like Example.varia and access object variables as self.varia? More on discuss.python.org
🌐 discuss.python.org
0
0
August 14, 2022
How to access class variable inside methods of that class in python? - Stack Overflow
Operating System: Windows, 64bit Python Version: 3.7.11 IDE: Jupyter Notebook (with conda env) I have below code: class Vocabulary(object): PAD_token = 0 def __init__(self): ... More on stackoverflow.com
🌐 stackoverflow.com
How to reference class variables inside class method
Do you ever set parameters? One, that type hint is actually for instance variables; despite the location, and two, the type hint doesn't create data. It's just a type hint. More on reddit.com
🌐 r/learnpython
11
2
November 5, 2022
How to refer to class methods when defining class variables in Python? - Stack Overflow
I have the following class and class variables: class MyClass: class_var_1 = "a" class_var_2 = run_class_method() @classmethod def run_class_method(cls): return "ran class More on stackoverflow.com
🌐 stackoverflow.com
People also ask

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 › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: Examples of Variables | 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 › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: Examples of Variables | Toptal®
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 › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: Examples of Variables | Toptal®
🌐
IONOS
ionos.com › digital guide › websites › web development › python class variables
How to create and use Python class variables
July 15, 2024 - Python class variables are created within the class de­f­i­n­i­tion and outside of methods. class Car: total_cars = 0 # Class variable to track the total number of cars def __init__(self, brand, model): self.brand = brand # Instance variable for the car brand self.model = model # Instance variable for the car model Car.total_cars += 1 # Increment the total number of cars upon each instantiation def display_details(self): print(f"Brand: {self.brand}, Model: {self.model}") # Creating instances of Car car1 = Car("BMW", "X3") car2 = Car("Audi", "A4") # Accessing class variable and instance variables print(f"Total number of cars: {Car.total_cars}") # Output: 2 car1.display_details() # Output: Brand: BMW, Model: X3 car2.display_details() # Output: Brand: Audi, Model: A4python
🌐
DigitalOcean
digitalocean.com › community › tutorials › understanding-class-and-instance-variables-in-python-3
Understanding Class and Instance Variables in Python 3 | DigitalOcean
August 20, 2021 - Defined outside of all the methods, class variables are, by convention, typically placed right below the class header and before the constructor method and other methods. Info: To follow along with the example code in this tutorial, open a Python interactive shell on your local system by running ...
🌐
Python.org
discuss.python.org › python help
Class variables - Python Help - Discussions on Python.org
August 14, 2022 - Hi, I am confused about class variable and instance variable in below example: class Classy: varia = 2 def method(self): print(self.varia, self.var) obj = Classy() obj.var = 3 obj.method() Don’t we access class …
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › how to reference class variables inside class method
r/learnpython on Reddit: How to reference class variables inside class method
November 5, 2022 -
class Test:
    config: Dict[str, str]
    parameters: Dict[str, str]

    def default(cls)
        return cls(
                parameters=get_params(),
                config=get_config(file="ATTRIBUTE FROM PARAMETERS"
        )
# I tried it like this:

class Test:
    config: Dict[str, str]
    parameters: Dict[str, str]

    def default(cls)
        return cls(
                parameters=get_params(),
                config=get_config(file=cls.parameters.config_file)
        )
# AttributeError: type object 'Test' has no attribute 'parameters'
Top answer
1 of 4
8

Class body in python is an executable context, not like Java that only contains declaration. What this ultimately means is that sequence of execution is important within a class definition.

To quote the documentation:

class definition is an executable statement.

...

The class’s suite is then executed in a new execution frame (see Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. [4] A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace.

Some more lengthier explanations.

If you want to call a function to define a class variable, you can do it with one of these ways:

  1. use staticmethod:

    class MyClass:
        def _run_instance_method():
            return "ran instance method"
        run_instance_method = staticmethod(_run_instance_method)
    
        class_var_1 = "a"
        class_var_2 = _run_instance_method() # or run_instance_method.__func__()
    
  2. or define it as a standalone function:

    def run_method():
        return "ran method"
    
    class MyClass:
        class_var_1 = "a"
        class_var_2 = run_method()
    
        # optional
        run_method = staticmethod(run_method)
    
  3. or access the original function with __func__ and provide a dummy cls value:

    class MyClass:
        @classmethod
        def run_class_method(cls):
            return "ran class method"
    
        class_var_1 = "a"
        class_var_2 = run_class_method.__func__(object())
    
  4. or set the class variables after class creation:

    class MyClass:
        @classmethod
        def run_class_method(cls):
            return "ran class method"
    
        class_var_1 = "a"
    
    MyClass.class_var_2 = MyClass.run_class_method()
    
2 of 4
3

MyClass is not yet defined when its class attributes are still being defined, so at the time class_var_2 is being defined, MyClass is not yet available for reference. You can work around this by defining class_var_2 after the MyClass definition block:

class MyClass:
    class_var_1 = "a"

    @classmethod
    def run_class_method(cls):
        return "ran class method"

MyClass.class_var_2 = MyClass.run_class_method()
🌐
Toptal
toptal.com › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: Examples of Variables | Toptal®
January 16, 2026 - Then, when we access foo.class_var, class_var has a new value in the class namespace and thus 2 is returned. If a Python class variable is set by accessing an instance, it will override the value only for that instance.
🌐
Npblue
npblue.com › tech › python › oop › class-variables-and-methods
Class Variables and `@classmethod` in Python with Real-World Examples
A class variable is a variable that is shared across all instances of a class. It is defined inside the class but outside any instance methods. All objects of the class have access to the same copy of this variable.
🌐
Dive into Python
diveintopython.org › home › learn python programming › classes in python › class variables, attributes, and properties
Class Variables and Properties in Python: Public, Private and Protected
May 3, 2024 - Properties: A property is a way to define a method as an attribute. Properties are created using the @property decorator. In Python, class variables are a powerful way to share data among all instances of a class.
🌐
GeeksforGeeks
geeksforgeeks.org › python-using-variable-outside-and-inside-the-class-and-method
Python | Using variable outside and inside the class and method - GeeksforGeeks
May 18, 2020 - In simple terms, variables are names attached to particular objects in Python. To create a variable, you just need to assign a value and then start using it. The assignment is done with a single equals sign (=): Python3 # Variable named age ...
🌐
Career Karma
careerkarma.com › blog › python › python class variables vs. instance variables
Python Class Variables vs. Instance Variables | Career Karma
December 1, 2023 - A Python class variable is shared by all object instances of a class. Class variables are declared when a class is being constructed. They are not defined inside any methods of a class.
🌐
GeeksforGeeks
geeksforgeeks.org › python › g-fact-34-class-or-static-variables-in-python
Class (Static) and Instance Variables in Python - GeeksforGeeks
2 weeks ago - Class variables can be modified in two ways. However, only one method is recommended because it avoids confusion. ... When we change the class variable using an object (a.stream), Python does not change the class variable. Instead, it creates a new instance variable only for a.
🌐
CBT Nuggets
cbtnuggets.com › blog › technology › programming › python-class-variables-explained
Python Class Variables: Explained
May 9, 2023 - In computer science, the scope of a variable is the area or namespace in which the variable binding is valid. So that means all methods within a class will be able to use class variables.
Top answer
1 of 4
65

This is because of the way Python resolves names with the .. When you write self.list the Python runtime tries to resolve the list name first by looking for it in the instance object, and if it is not found there, then in the class instance.

Let's look into it step by step

self.list.append(1)
  1. Is there a list name into the object self?
    • Yes: Use it! Finish.
    • No: Go to 2.
  2. Is there a list name into the class instance of object self?
    • Yes: Use it! Finish
    • No: Error!

But when you bind a name things are different:

self.list = []
  1. Is there a list name into the object self?
    • Yes: Overwrite it!
    • No: Bind it!

So, that is always an instance variable.

Your first example creates a list into the class instance, as this is the active scope at the time (no self anywhere). But your second example creates a list explicitly in the scope of self.

More interesting would be the example:

class testClass():
    list = ['foo']
    def __init__(self):
        self.list = []
        self.list.append('thing')

x = testClass()
print x.list
print testClass.list
del x.list
print x.list

That will print:

['thing']
['foo']
['foo']

The moment you delete the instance name the class name is visible through the self reference.

2 of 4
10

Python has interesting rules about looking up names. If you really want to bend your mind, try this code:

class testClass():
    l = []
    def __init__(self):
        self.l = ['fred']

This will give each instance a variable called l that masks the class variable l. You will still be able to get at the class variable if you do self.__class__.l.

The way I think of it is this... Whenever you do instance.variable (even for method names, they're just variables who's values happen to be functions) it looks it up in the instance's dictionary. And if it can't find it there, it tries to look it up in the instance's class' dictionary. This is only if the variable is being 'read'. If it's being assigned to, it always creates a new entry in the instance dictionary.

Top answer
1 of 2
772

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

2 of 2
25

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello
World
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

🌐
ITU Online
ituonline.com › itu online › blogs › python class variables: declaration, usage, and practical examples
Python Class Variables: Declaration, Usage, And Practical Examples - ITU Online IT Training
August 3, 2023 - A class variable is shared among all instances of the class, while an instance variable is unique to each instance. Class variables are defined outside of any method in the class, while instance variables are defined inside methods or the init ...