what happens when we call a class?

Viewed 370

From python in a nutshell,

Where C is a class, the statement x=C(23) is equivalent to:

x = C.__new__(C, 23) 
if isinstance(x, C): type(x).__init__(x, 23)

From my understanding object.__new__ creates a new, uninitialized instance of the class it receives as its first argument.

Why is there need to be a check with the isinstance(). Isn't it obvious that __new__ will return a object of type C.

If it is what happens if this test fails?

Since classes are callables, is the call to __new__ is done in the class's __call()__ method

Am I missing something here, please clarify this to me

2 Answers

Isn't it obvious that __new__ will return a object of type C.

Not at all. The following is valid:

>>> class C:
...   def __new__(cls):
...     return "not a C"
...   def __init__(self):
...     print("Never called")
...
>>> C()
'not a C'

When you override __new__, you will probably return an instance of cls, but you aren't required to. This is useful for defining factory classes, which don't create instances of themselves but rather instances of other classes.

Note that you quote is not quite accurate. x = C(32) is equivalent, at the first step, to x = type.__call__(C, 32). It is type.__call__ that calls C.__new__, then decides whether to invoke the return value's __init__ method.

You can think of type.__call__ as being defined something like

def __call__(cls, *args, **kwargs):
    obj = cls.__new__(cls, *args, **kwargs)
    if isinstance(obj, cls):
        obj.__init__(*args, **kwargs)
    return obj

Applying this to C, we see that obj is set to the str value 'not a C', not an instance of C, so that 'not a C'.__init__ is not called before returning the string.

isinstance(a, b) is used to check if a is instance of b. Not sure why you checking it after creation. Magical methods can be redefined. Although in normal cases isinstance() is needed to check dynamic data.

Related