demonguy demonguy - 2 months ago 13
Python Question

Does import call __new__ static method?

I know that

__new__
method is called when attempt to create an instance of a class before
__init__
is called.

But i happened to find that, import a module withou create instance will also call
__new__


suppose i have this:

a.py:

import abc
class A(abc.ABCMeta):
def __new__(cls, name, bases, namespace):
print("ttt:", cls, name, bases, namespace)
retval = abc.ABCMeta.__new__(cls, name, bases, namespace)
return retval


class B(object):
__metaclass__ = A


and

b.py

import a

class C(B):
def a():
pass


Then i execute
python b.py
, i can see two
ttt
print by
__new__
.
So, when does the new exactly called, in this case, i never create any instance of the three classes i defined

Answer

When you use a metaclass to define a class, the metaclass is "called" implicitly (which invokes __new__ since the metaclass here is an actual class), see Invoking the metaclass. I can't say why you see three prints here (you only have two classes that uses A as a metaclass, directly or indirectly through inheritance), but that explains two of the prints.

Comments