Yes, a class can contain an instance of itself, you just can't create it on initiation for the reasons described by others.

For example, this class will do it:

class A:
    def __init__(self, value):
        self.value = value

    def setProperty(self, subvalue):
        self.innerInstance = A(subvalue)

You can then instantiate it and set its inner copy of itself like this:

>>> outerInstance = A(123)
>>> outerInstance.setProperty(456)

And verify it worked with:

>>> outerInstance.innerInstance.value
456
Answer from D Maxwell on Stack Overflow
Top answer
1 of 4
9

Yes, a class can contain an instance of itself, you just can't create it on initiation for the reasons described by others.

For example, this class will do it:

class A:
    def __init__(self, value):
        self.value = value

    def setProperty(self, subvalue):
        self.innerInstance = A(subvalue)

You can then instantiate it and set its inner copy of itself like this:

>>> outerInstance = A(123)
>>> outerInstance.setProperty(456)

And verify it worked with:

>>> outerInstance.innerInstance.value
456
2 of 4
8

This won't work, for the reason already given:

  1. Python sees A(2) and calls A.__init__.
  2. A.__init__ calls A(val).
  3. A(val) calls A.__init__.
  4. GOTO 2

I assume you're doing this so that you have a log of what val has been; that is, if sometime later you decide that you want val to be 3 instead, you don't throw away the original value 2. How about:

Code

class A( object ):
    @property
    def val( self ):
        return self.history[ -1 ]

    @val.setter
    def val( self, value ):
        self.history.append( value )

    def __init__( self, val ):
        self.history = [ ]
        self.val = val

Explanation

  • A( object ): classes should now inherit from object. Just because, basically.
  • @property: this tells python that every time we ask for A.val, it should call A.val() and return the result. This is a decorator; look up the property builtin function for more information.
  • @val.setter: this is similar to the above, but tells Python that every time we try to assign to A.val it should call the following function instead. Instead of setting A.val, it appends the value to the history list.
๐ŸŒ
Real Python
realpython.com โ€บ python-class-constructor
Python Class Constructors: Control Your Object Instantiation โ€“ Real Python
October 21, 2025 - A class constructor in Python is a mechanism that creates and initializes a new instance of a class. It involves calling the class itself like a function, which triggers the instantiation process, including the execution of the .__new__() and ...
Discussions

Understanding classes, init and self
Could you explain this code excerpt? I am learning and trying to get in touch with the logic of classes ยท The __init__ method initialises a new instance (object) of the class NewWindow. The actual creation of the instance is done by a separate method __new__, before __init__ is called. More on discuss.python.org
๐ŸŒ discuss.python.org
19
0
February 16, 2024
python - Create new object (class instance) from object method - Stack Overflow
I want to be able to create a new instance of an object by calling a method on an already instantiated object. For example, I have the object: organism = Organism() I want to be able to call orga... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is there a way of instantiating a class inside a class
Yup, just like you would outside a class. class A: def __init__(self): self.b = B() class B: def __init__(self): self.x =1 a = A() print(a.b.x) More on reddit.com
๐ŸŒ r/learnpython
3
1
March 10, 2023
python - Class variable that is an instance of itself - Stack Overflow
Is something like this possible? class Foo: BAR = Foo("bar") def __init__(self, name): self.name = name Currently this yields NameError: name 'Foo' is not defined. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ classes.html
9. Classes โ€” Python 3.14.8 documentation
1 week ago - Class attributes can also be assigned to, so you can change the value of MyClass.i by assignment. __doc__ is also a valid attribute, returning the docstring belonging to the class: "A simple example class". Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class): ... The instantiation operation (โ€œcallingโ€ a class object) creates an empty object.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Understanding classes, init and self - Python Help - Discussions on Python.org
February 16, 2024 - I am learning and trying to get in touch with the logic of classes ยท The __init__ method initialises a new instance (object) of the class NewWindow. The actual creation of the instance is done by a separate method __new__, before __init__ is called.
๐ŸŒ
Medium
medium.com โ€บ quick-code โ€บ support-your-class-users-by-providing-an-alternate-way-of-creating-class-instances-using-class-e2da42241913
Support your class users by providing an alternate way of creating class instances using classโ€ฆ
November 17, 2020 - Use class methods to generate objects generically in python when the __init__ method doesnโ€™t support all the ways you want class users to be able to create instances of a class Class methods are โ€ฆ
๐ŸŒ
GitHub
github.com โ€บ pydantic โ€บ pydantic โ€บ discussions โ€บ 2792
Create Python class which contains a list of instances of itself ยท pydantic/pydantic ยท Discussion #2792
To each node I must attach a list of other nodes, either Decision or Random node. Where I'm stucked is how to structure the classes efficiently in order to be able to have any kind of structured nodes which each node can ve a list of other nodes, like those shown on the images above.
Author: pydantic
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ creating-instance-objects-in-python
Creating Instance Objects in Python - GeeksforGeeks
July 23, 2025 - In Python, an instance object is an individual object created from a class, which serves as a blueprint defining the attributes (data) and methods (functions) for the object. When we create an object from a class, it is referred to as an instance.
Find elsewhere
๐ŸŒ
Python Like You Mean It
pythonlikeyoumeanit.com โ€บ Module4_OOP โ€บ ClassInstances.html
Instances of a Class โ€” Python Like You Mean It
Each of these instances share the common attributes append, count, reverse, and so on, as specified in the definition of Pythonโ€™s list class, which is encapsulated by the list class object. That being said, the specific content of any given list is an attribute of that particular list instance; that is, the content of a particular list is an instance attribute rather than a class attribute. Thus far, we do not have the ability to create instance-level attributes.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ is there a way of instantiating a class inside a class
r/learnpython on Reddit: Is there a way of instantiating a class inside a class
March 10, 2023 -

I have written some code and have now realised I should not have used independent functions and call them at the right time, but rather should have used classes and constructs and what not. some functions work together with other functions but do completely different things, so putting them in the same class or in parent child or sister relationship wont work or be appropriate. So is there a way of instantiating a class inside another class

๐ŸŒ
Open Book Project
openbookproject.net โ€บ thinkcs โ€บ python โ€บ english3e โ€บ classes_and_objects_I.html
15. Classes and Objects โ€” the Basics โ€” How to Think Like a Computer Scientist: Learning with Python 3
A function like Turtle or Point that creates a new object instance is called a constructor, and every class automatically provides a constructor function which is named the same as the class. It may be helpful to think of a class as a factory for making objects. The class itself isnโ€™t an instance of a point, but it contains the machinery to make point instances.
๐ŸŒ
DEV Community
dev.to โ€บ ogwurujohnson โ€บ creating-and-instantiating-a-simple-class-in-python-79b
Python Instantiate Class: Creating and Instantiating a simple class in python - DEV Community
November 29, 2017 - To create instance variables for ... an employee would mean having a-lot of code and errors. But python allows you to be able to create instances automatically and this we could do using its (init) method....
Top answer
1 of 5
183

I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.

class k:
  pass

a = k()
k2 = a.__class__
a2 = k2()

At this point, a and a2 are both instances of the same class (class k).

2 of 5
26

Just call the "type" built in using three parameters, like this:

ClassName = type("ClassName", (Base1, Base2,...), classdictionary)

update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.

To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:

instance = ClassObject()

The mechanism for instantiation is thus:

Python does not use the new keyword some languages use - instead its data model explains the mechanism used to create an instance of a class when it is called with the same syntax as any other callable:

Its class' __call__ method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type). The normal behavior of this call is to invoke the (pseudo) static __new__ method on the class being instantiated, followed by its __init__. The __new__ method is responsible for allocating memory and such, and normally is done by the __new__ of object which is the class hierarchy root.

So calling ClassObject() invokes ClassObject.__class__.call() (which normally will be type.__call__) this __call__ method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is, of course, done in C, and with lots of extra code for cornercases and optimizations)

class type:
    ...
    def __call__(cls, *args, **kw):
          constructor = getattr(cls, "__new__")
          instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
          instance.__init__(cls, *args, **kw)
          return instance

(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__ and passing it to other classes - but it is what happens "in real life" - if object.__new__ is called with any extra parameters it raises a type error - however, any custom implementation of a __new__ will get the extra parameters normally)

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ forming a new instance through class method
r/learnpython on Reddit: Forming a new instance through class method
September 4, 2025 - Technically speaking, instance creation is a two-step process in Python. MyClass() is technically equivalent to MyClass.__new__(), and __new__ handles the actual creation process.
Top answer
1 of 4
7

Well, it fails because it has infinite recursion. Think about it, if every MyClass has a child which is a MyClass, it will go on for infinity!

You can resolve this a couple of ways. First, you can have a parameter to the constructor:

class MyClass:
   def __init__(self, create = True):
      if create:
         self.child = MyClass(False)

mc = MyClass()

Or, you can have another, external method:

class MyClass:
    def set_child(self,child = None):
        # I prefer to make child optional for ease of use.
        child = MyClass() if child is None else child
        self.child=child

mc=MyClass()
mc.set_child()

I personally prefer the first solution as it means that outside objects don't need to know anything about the class. Of course, you could combine the two:

class MyClass:
    def __init__(self, create):
        if create:
            self.set_child(create=False)

    def set_child(self,child = None, create = True):
        child = MyClass(create) if child is None else child
        self.child=child

mc=MyClass()

This way mc has a child by default and you have the option of setting the child whenever you like.

Then there is also the "let's create a certain number" approach:

class MyClass:
    def __init__(self, count = 10):
        count -= 1
        if count:
           # the first child gets the value 9.
           # the second gets 8.
           # when the count gets to 0, stop!
           self.child = MyClass(count)

Aside: If you want to get an object's class, you can use the value obj.__class__. That will output MyClass in all of the examples above.

2 of 4
5

You're making an infinitely recursing call โ€” MyClass is creating another MyClass during initialization, and thus it recurses infinitely.

You may want to do something like:

class MyClass:
    def create_child(self):
        self.child=MyClass()

mc=MyClass()
mc.create_child()

If you're feeling particularly naughty, you could try:

class MyClass(object):
    @property
    def child(self):
        if self._child is None: self._child = MyClass()
        return self._child

    def __init__(self):
        self._child=None

mc=MyClass()
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ self-in-python-class
self in Python class - GeeksforGeeks
February 26, 2025 - In Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance.
Top answer
1 of 3
19

Given a Python class which will be instantiated only once, i.e. there will be only one object of the class. I was wondering in which cases it makes sense to create a single class instance instead of working directly with the class instead.

So it's this:

class Singleton:
    '''don't bother instantiating me'''
    clsvar1 = 'foo'

    @classmethod
    def foobar(cls, *args, **kwargs):
        if condition():
            cls.clsvar1 = 'bar'

versus this?

class Singleton:
    '''instantiate and use me'''
    def __init__(self):
        self.var1 = 'foo'

    def foobar(self, *args, **kwargs):
        if condition():
            self.var1 = 'bar'

Recommendation

I definitely would prefer the one that's intended to be instantiated. When you create a "type of thing" that implies that you create things of that type.

The motivation is to group related code and data and having an interface to it.

That said, why not just use a module since all you want is a namespace? Modules are singletons, group related code and data, and this is a bit simpler and probably would be considered more Pythonic:

var1 ='foo'

def foobar(*args, **kwargs):
    global var1
    if condition():
        var1 = 'bar'

So the usage would be instead of:

from modules.singleton import Singleton
Singleton.foobar()

or

from modules.singleton import Singleton
the_singleton = Singleton()
the_singleton.foobar()

do this:

from modules import singleton
singleton.foobar()
2 of 3
4

I was wondering in which cases it makes sense to create a single class instance instead of working directly with the class instead.

This is one of those things that will cause a religious war if you get into it to much.

But in general a practice that I have seen many times is that class methods should concern themselves only with creating instances of that class.

If you think about what a class is, what its purpose/behaviour is, then this makes sense. The purpose of a class is to create instances of objects that are based on itself. It is a blueprint that can also build the building. A "User" class creates "user" objects. A "Dog" class creates "dog" objects etc etc

Give this is the behaviour of a class it makes sense then that methods you add to the class "X" will concern themselves with creating "x" objects.

So even if you are only ever going to need one "x" object you should still instanciate it.

Adding methods to the X class that are not related to creating instances of "x" objects can lead to confusing unexpected code. There are of course tons of examples in the real world where people have done this anyway, but like I said that path leads to religious war.