demonguy demonguy - 8 months ago 55
Python Question

Does import call __new__ static method?

I know that

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

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

suppose i have this:

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


import a

class C(B):
def a():

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


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.