-3

Normally an instance can be created with something like:

class New:
    def __new__(cls, *args, **kwargs):
        # placeholder
        return super().__new__(cls)
    def __init__(self, name):
        self.name = name

>>> n=New('bob')
>>> n
<__main__.New object at 0x103483550>

What occurs behind the scenes here? For example, something like:

new_uninitialized_obj = object.__new__(New)
new_initialized_obj = new_uninitialized_obj.__init__("Bob")

The above won't work, but I'm basically just trying to see how a base type is converted via new and then init into the instance object. How would this actually be done?

David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

-1

__init__ does not return anything but only updates the instance that has been created in __new__, so you can do something like the following to create a new instance and initialize it:

new_obj = object.__new__(New)
# We can see it creates a new object of class `New`
>>> new_obj
<__main__.New object at 0x103483e10>
>>> new_obj.__dict__
{}

new_obj.__init__("Bob")
# now we update the object attributes based on init
>>> new_obj.__dict__
{'name': 'Bob'}
David542
  • 104,438
  • 178
  • 489
  • 842