The answer is "yes, but…"

The best way to understand is to actually try it:

>>> class RLCN:
...     static_var = 5
...     def method1(self):
...         RLCN.static_var += 1
...     def method2(self):
...         self.static_var += 1
>>> rlcn = RLCN()
>>> RLCN.static_var, rlcn.static_var
(5, 5)
>>> rlcn.static_var
5
>>> rlcn.method1()
>>> RLCN.static_var, rlcn.static_var
(6, 6)
>>> rlcn.method2()
>>> RLCN.static_var, rlcn.static_var
(6, 7)

What happened?

Well, accessing a class attribute through self works just fine. If there is no instance attribute of the same name, you get the class attribute.

But assigning to it will hide the class attribute with a new instance attribute of the same name. Which is probably not what you wanted.

Note that this means you can use class attributes as "default values" or "initial values" for instance attributes. But I'm not sure it's very Pythonic to do so; what's actually happening, and what a novice (especially someone coming from, e.g., C++11 or Java) thinks is happening, are very different.

(Things get slightly more complicated when you deal with descriptors, like methods or @propertys, but let's ignore that; in the simple case that you're discussing, it's not relevant.)


I'd rather do something like class(self).static_var += 1, because long names are unreadable.

You can, you just need to spell it right: type is the function that returns the type of any object. So:

type(self).static_var += 1

This has the added advantage of being dynamic (e.g., when you have multiple inheritance and don't know which side a @property comes from, you probably don't want to explicitly list a class name, for basically the same reason you want to use super() instead of explicitly calling a base class method).

This has the disadvantage of not working on old-style classes in Python 2.x, but then you shouldn't be using those anyway. Especially in classes that have a need for class attributes, because those are exactly the types you're often going to later want to add @classmethods, @propertys, etc. to, and none of that works with old-style classes (along with many other things). If you really need to handle old-style and new-style classes transparently for some reason, self.__class__ is works with old-style classes. I'm not sure it's guaranteed to work with new-style classes; the docs say that the return value of type(object) is "generally the same object as returned by object.__class__", but doesn't say under what conditions that "generally" is untrue. It's also documented as a special attribute "added by the implementation" for "several object types" in 3.x. In practice, I don't know of any cases where they're different in 3.x, and in 2.x, the most prominent case where they're different is old-style classes.

Answer from abarnert on Stack Overflow
Top answer
1 of 2
81

The answer is "yes, but…"

The best way to understand is to actually try it:

>>> class RLCN:
...     static_var = 5
...     def method1(self):
...         RLCN.static_var += 1
...     def method2(self):
...         self.static_var += 1
>>> rlcn = RLCN()
>>> RLCN.static_var, rlcn.static_var
(5, 5)
>>> rlcn.static_var
5
>>> rlcn.method1()
>>> RLCN.static_var, rlcn.static_var
(6, 6)
>>> rlcn.method2()
>>> RLCN.static_var, rlcn.static_var
(6, 7)

What happened?

Well, accessing a class attribute through self works just fine. If there is no instance attribute of the same name, you get the class attribute.

But assigning to it will hide the class attribute with a new instance attribute of the same name. Which is probably not what you wanted.

Note that this means you can use class attributes as "default values" or "initial values" for instance attributes. But I'm not sure it's very Pythonic to do so; what's actually happening, and what a novice (especially someone coming from, e.g., C++11 or Java) thinks is happening, are very different.

(Things get slightly more complicated when you deal with descriptors, like methods or @propertys, but let's ignore that; in the simple case that you're discussing, it's not relevant.)


I'd rather do something like class(self).static_var += 1, because long names are unreadable.

You can, you just need to spell it right: type is the function that returns the type of any object. So:

type(self).static_var += 1

This has the added advantage of being dynamic (e.g., when you have multiple inheritance and don't know which side a @property comes from, you probably don't want to explicitly list a class name, for basically the same reason you want to use super() instead of explicitly calling a base class method).

This has the disadvantage of not working on old-style classes in Python 2.x, but then you shouldn't be using those anyway. Especially in classes that have a need for class attributes, because those are exactly the types you're often going to later want to add @classmethods, @propertys, etc. to, and none of that works with old-style classes (along with many other things). If you really need to handle old-style and new-style classes transparently for some reason, self.__class__ is works with old-style classes. I'm not sure it's guaranteed to work with new-style classes; the docs say that the return value of type(object) is "generally the same object as returned by object.__class__", but doesn't say under what conditions that "generally" is untrue. It's also documented as a special attribute "added by the implementation" for "several object types" in 3.x. In practice, I don't know of any cases where they're different in 3.x, and in 2.x, the most prominent case where they're different is old-style classes.

2 of 2
78

Use self.__class__.classAttr. This should work for both old & new style classes.

🌐
PYnative
pynative.com › home › python › python object-oriented programming (oop) › python class variables
Python Class Variables With Examples – PYnative
September 8, 2023 - In Python, we can access the class variable in the following places · Access inside the constructor by using either self parameter or class name. Access class variable inside instance method by using either self of class name · Access from ...
🌐
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 - Just like with any other variable, class variables can consist of any data type available to us in Python. In this program we have strings and an integer. Let’s run the program again with the python shark.py command and review the output: ... The instance of new_shark is able to access all the class variables and print them out when we run the program.
🌐
Reddit
reddit.com › r/learnpython › opinions about accessing (and setting) instance variables
r/learnpython on Reddit: Opinions about accessing (and setting) instance variables
June 2, 2023 -

I'm currently working on a linguistic project involving numerous data, classes, and thus instance variables (or properties) which I expect to grow in number after some significant progress.

So far, I've known three ways on getting and setting instance variables in all my classes:

  1. Directly getting/setting an instance variable using the instance keyword self, e.g. self.my_variable

  2. Using getter and setter methods, e.g. set_my_variable() and get_my_variable()

  3. Using the @property decorator for methods that act as the instance variable themselves

I've been using the third way to define my classes by enclosing the instances' attributes in underscored variables (e.g. self._foo) and later on declaring property methods to gain access to those variables.

I admit that it may get too messy later on when my package expands, and having little confidence with my code, I just want to know which of the three do you usually use and do you have any recommendations as to which should be preferred?

🌐
GeeksforGeeks
geeksforgeeks.org › python › different-ways-to-access-instance-variable-in-python
Different ways to access Instance Variable in Python - GeeksforGeeks
July 12, 2025 - Python3 · #creating class class student: # constructor def __init__(self, name, rollno): # instance variable self.name = name self.rollno = rollno def display(self): # using self to access # variable inside class print("hello my name is:", self.name) print("my roll number is:", self.rollno) # Driver Code # object created s = student('HARRY', 1001) # function call through object s.display() # accessing variable from # outside the class print(s.name) Output: hello my name is: HARRY my roll number is: 1001 HARRY ·
🌐
Reddit
reddit.com › r/learnpython › how can i access a variable containing a class instance from another class located in another python file? (what a jumble of words)
r/learnpython on Reddit: How can I access a variable containing a class instance from another class located in another python file? (what a jumble of words)
January 12, 2023 -

in main.py I have a class called "Game", and a variable containing an instance of that class, called "game". In another file called SpriteClass.py I have a class that contains a function where I need to access the variables from the Game instance. I tried importing main.py, but whenever I do that, and write main.game.variableName I get a warning from Pycharm saying Cannot find reference 'game' in 'main.py'

Since this function in SpriteClass.py is going to be run in the Game class in main.py I also tried making an argument where I could input the variable containing the Game class reference, but even in the Game class it couldn't find the reference to the "game" variable.

Is there something I am doing wrong? How am I supposed to get access to the class instance variable from main.py into SpriteClass.py?

Here are the relevant files:

https://pastebin.com/Dr6kYZhH

https://pastebin.com/GQckCNDf

🌐
W3Resource
w3resource.com › python-interview › how-to-access-instance-variables-within-python-class-methods.php
How to access instance variables within Python class methods?
Example: Access instance variables within a class method · class Student: def __init__(self, value): self.instance_var = value def display(self): print("Instance variable value:", self.instance_var) def update_instance_var_value(self, new_value): self.instance_var = new_value # Create an object of Student std_obj = Student(12) # Access and display instance variable using the display() method std_obj.display() # Output: Instance variable value: 12 # Update instance variable using the update_instance_var() method std_obj.update_instance_var_value(14) # Display instance variable again to see the updated value std_obj.display() # Output: Instance variable value: 14
Find elsewhere
🌐
DEV Community
dev.to › ogwurujohnson › distinguishing-instance-variables-from-class-variables-in-python-81
Python Class Variables: Distinguishing Instance Variables from Class Variables in python - DEV Community
November 29, 2017 - We get the-same output, which proves that class variables could be accessed by your class and at the-same time instances of the class. So what happens here is that when we try to access an attribute on an instance, it first checks whether the instance contains the attribute; if it doesn't, it checks if the parent class or any class it inherits from contains the attributes; so when we access (raise_amount) from our instances, they don't actually have that attribute but rather they are accessing the classes the (raise_amount) variable attributes.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-update-class-variable
How to Update or access Class variables in Python | bobbyhadz
Updating the cls_id class variable is reflected in all instances. You can use the type() class if you need to access a class variable from an instance of the class.
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
If the name denotes a valid class attribute that is a function object, references to both the instance object and the function object are packed into a method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list. Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:
🌐
IONOS
ionos.com › digital guide › websites › web development › python class variables
How to create and use Python class variables
July 15, 2024 - In Python, you can access class ... or the class name. In instance methods: You can call the class variable in instance methods using either the self keyword or the class name....
Top answer
1 of 5
184

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

2 of 5
14

You are declaring a local variable, not a class variable. To set an instance variable (attribute), use

class Example(object):
    def the_example(self):
        self.itsProblem = "problem"  # <-- remember the 'self.'

theExample = Example()
theExample.the_example()
print(theExample.itsProblem)

To set a class variable (a.k.a. static member), use

class Example(object):
    def the_example(self):
        Example.itsProblem = "problem"
        # or, type(self).itsProblem = "problem"
        # depending what you want to do when the class is derived.
🌐
Squash
squash.io › how-to-use-class-and-instance-variables-in-python
How to Use Class And Instance Variables in Python
Related Article: How To Merge Dictionaries In Python · One common use case for class variables is to store data that is shared among all instances of a class. For example, you might have a Car class that needs to keep track of the number of wheels for all cars. ... class Car: wheels = 4 def __init__(self, color): self.color = color # Accessing a class variable through an instance car1 = Car("red") car2 = Car("blue") print(car1.wheels) # Output: 4 print(car2.wheels) # Output: 4 # Modifying a class variable using the class name Car.wheels = 6 print(car1.wheels) # Output: 6 print(car2.wheels) # Output: 6
🌐
Stack Overflow
stackoverflow.com › questions › 31880378 › accessing-class-method-vairable-in-instance-method
python - Accessing class method vairable in instance method - Stack Overflow
I would like to know how to access the class variable cls.name in my instance method - parent_method. class Parent(): def __init__(self): print "Parent initialized" @classmethod def resource_setup(cls): cls.name = "P" print "parent method" def parent_method(self): print self.name ... You need to call that class method in order for the name to come into existence. BTW, since you're using Python 2 you should explicitly derive your classes from object, otherwise you get old-style classes.
🌐
PYnative
pynative.com › home › python › python object-oriented programming (oop) › python instance variables explained with examples
Python Instance Variables With Examples – PYnative
October 21, 2021 - Let’s see the example to declare an instance variable in Python. ... In the following example, we are creating two instance variable name and age in the Student class. class Student: # constructor def __init__(self, name, age): # Instance variable self.name = name self.age = age # create first object s1 = Student("Jessa", 20) # access instance variable print('Object 1') print('Name:', s1.name) print('Age:', s1.age) # create second object s2= Student("Kelly", 10) # access instance variable print('Object 2') print('Name:', s2.name) print('Age:', s2.age) Code language: Python (python) Run