If I understand your question correctly, you should be able to reference class A within class A by putting the type annotation in quotes. This is called forward reference.

class A:
  # do something
  def some_func(self, a: 'A')
  # ...

See ref below

  1. https://github.com/python/mypy/issues/3661
  2. https://www.youtube.com/watch?v=AJsrxBkV3kc
Answer from Chin Pang Yau on Stack Overflow
๐ŸŒ
GitHub
github.com โ€บ python โ€บ mypy โ€บ issues โ€บ 3661
Type of the same class inside the class ยท Issue #3661 ยท python/mypy
July 5, 2017 - I have a method that returns itself but it doesn't know the type of the class inside class TcpFlow(object): def __init__(self) -> None: self.matches = [] # type: List[str] def __enter__(self) -> TcpFlow: return self I got this error Trac...
Author: python
Top answer
1 of 3
19

You don't need to reference the class inside itself, using bar instead of Test.bar will work fine.

class Test:
    @staticmethod
    def bar():
        pass

    FOO_DICT = {1: bar}


# You can access this outside of the class by simply using Test.FOO_DICT
print(Test.FOO_DICT)

However, there are cases where you really need to use a class in itself. For example

class Test:
    @staticmethod
    def bar():
        pass

    def test_with_other_of_same_instance(self, other: Test):
        print(other.FOO_DICT)

    FOO_DICT = {1: bar}

In this case,

  • I want to define a method that accepts an object of the same Test class.
  • I want to use python's type hinting to indicate that the expected argument is an instance of Test. This allows me get editor support and also so tools like pylance and mypy can notify me of possible errors if I passed a argument of wrong data type.

As at the time of this writing, I'll get a NameError: name 'Test' is not defined.

This is because by default I can't use a class within itself (It is possible later versions of python will change its default behavior, hence we won't be needing the solution below by that time).

But if you use Python versions from 3.7+ and you can't reference a class within itself, the simple solution came with PEP 563 - Postponed evaluation of annotations. It is implemented by adding a little line of code at the first line of the file

from __future__ import annotations
# other imports or code come afterwards


class Test:
    @staticmethod
    def bar():
        pass

    def test_with_other_of_same_instance(self, other: Test):
        print(other.FOO_DICT)

    FOO_DICT = {1: bar}

So you can use a class within itself in python by simply including that line at the beginning of the file.

Normally, if you use pylance or any similar tool, you get a warning or error display to show you that you imported something and didn't use it. But not in the case of annotations. You don't have to worry about any warning from your editor.

Note that this must occur at the beginning of the file otherwise you get a SyntaxError and versions earlier than 3.7 won't support this.

2 of 3
5

If you want the dictionary to be in the class: define the function first and remove Test:

class Test:
    @staticmethod
    def bar():
         pass

    FOO_DICT = {1: bar}
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ classes.html
9. Classes โ€” Python 3.14.8 documentation
1 week ago - Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have ...
๐ŸŒ
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'
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ are nested classes a thing?
r/learnpython on Reddit: Are nested classes a thing?
July 3, 2022 -

I'm fairly new to OOP in Python, and am toying with the idea of making a 2D world that appears 3D by moving things at different rates. Simple enough.

But I find myself wondering if there are times when defining classes within classes is useful. For example, a "layer" object might be something defined within a "viewer" object.

If things are done this way, are there ways for a nested class to have access to methods or attributes of an overarching class? (I was thinking that the "layers" might all have access to where the "viewer" is so that they know how to present themselves. Each "layer" would calculate this for itself, since parallax would change based on apparent distance of that "layer" from the player, but it would all be based on positional attributes the "viewer" has.)

Or is there some better way to organize this? I'm curious to know what kind of organizational decisions people might make and why.

Thank you for sharing your thoughts and/or resources on this.

Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ inner-class-in-python
Inner Class in Python - GeeksforGeeks
July 15, 2025 - ... First, we create a class and then the constructor of the class. After creating a class, we will create another class within that class, the class inside another class will be called an inner class.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-15131.html
Calling a class inside other class
class Class1: def __init__(self): self.atr1 = value1 self.atr2 = value2 def method_1(self): ??? class Class2: def __init__(self): self.atr_new = ??? def method_2(self): ...Hi, I want these
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ inner-classes-python
Python Nested & Inner Classes | DataCamp
January 3, 2020 - They are all together. Inner or Nested classes are not the most commonly used feature in Python. But, it can be a good feature to implement code.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to refer to current class object - Python Help - Discussions on Python.org
August 16, 2026 - Is there some way I can refer to the current class object from within itself before itโ€™s definition is completed? I have found a number of times where it would be very useful to be able to reference the currently runninโ€ฆ
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to refer to current class object - Page 2 - Python Help - Discussions on Python.org
August 16, 2026 - It is rather the name "myClass", a str, assigned as the value of the key __qualname__, right? {'__module__': '__main__', '__qualname__': 'myClass', '__firstlineno__': 1, 'var': 0} If you had, for example, in your scope a variable x = 3, you would see in locals() a key "x" and the value 3 associated to it.
Top answer
1 of 2
3

You cannot refer to MetaDataElement while it is being constructed, since it does not yet exist. Thus,

class MetaDataElement:
    (MD_INVALID, MD_CATEGORY, MD_TAG) = range(3)
    mapInitiator2Type = {'!':MetaDataElement.MD_CATEGORY, 
                         '#':MetaDataElement.MD_TAG}

fails because the very construction of mapInitiator2Type requires MetaDataElement to have attributes, which it does not yet have. You can think of your constants MD_INVALID, etc. as variables that are local to the construction of your class. This is why the following works, as icktoofay wrote:

class MetaDataElement:
    (MD_INVALID, MD_CATEGORY, MD_TAG) = range(3)
    mapInitiator2Type = {'!': MD_CATEGORY,  # MD_CATEGORY is like a local variable!
                         '#': MD_TAG}

However, you can refer to the class MetaDataElement in any yet un-interpreted piece of code, as in

    def method_of_MetaDataElement(self):
        print MetaDataElement.MD_TAG

You even have to refer to MetaDataElement, here, because MD_TAG is not a kind of local variable when method_of_MetaDataElement() is executed (MD_TAG was only defined as a kind of local variable during class construction). Once the class MetaDataElement is created, MD_TAG is simply a class attribute, which is why method_of_MetaDataElement() must refer to it as such.

2 of 2
1

First of all, you're using old-style classes. You should probably use new-style classes, like so:

class MetaDataElement(object):
    ...

Note the (object). Anyway, though, simply remove the MetaDataElement. when referring to the class attributes. This is what it'd look like when that's done:

class MetaDataElement(object):
    (MD_INVALID, MD_CATEGORY, MD_TAG) = range(3)
    mapInitiator2Type = {'!': MD_CATEGORY, 
                         '#': MD_TAG}
๐ŸŒ
Medium
medium.com โ€บ @teamcode20233 โ€บ python-nested-class-a-comprehensive-guide-f3b64ede49ee
Python Nested Class: A Comprehensive Guide | by Teamcode | Medium
May 25, 2023 - In Python, a nested class is a class that is defined inside another class. The outer class is called the enclosing class, and the innerโ€ฆ
๐ŸŒ
Pythonspot
pythonspot.com โ€บ inner-classes
Python Inner Class โ€” Tutorial with Examples | Pythonspot
January 1, 2026 - Free tier available. An inner class or nested class is a defined entirely within the body of another class. If an object is created using a class, the object inside the root class can be used.