[Tutor] How to know the internal execution flow of class

Deepak Dixit deepakdixit0001 at gmail.com
Sat Feb 15 10:08:15 EST 2020


Hi Tutors,

What happens when we create a class or function. In other way, I want to
know the life-cycle of class. Lets see an example:

######### Script Start #########

class MClass(type):
    def __new__(cls, *args):
        print 'New from MClass', args[0]
        return super(MClass, cls).__new__(cls, *args)

class A:
    print 'Class A defined'
    __metaclass__ = MClass

    def __init__(self, *args):
        print 'Init from A', args

    def __new__(cls, *args):
        print 'New from A', args
        return super(A, cls).__new__(cls, *args)

print 'Class A definition end'
a = A()
print 'Object created: A'

class B:
    print 'Class B defined'
    __metaclass__ = MClass

    def __init__(self, *args):
        print 'Init from B', args

    def __new__(cls, *args):
        print 'New from B', args

print 'Class B definition end'
b = B()
print 'Object created: B'

######### Script End #########

#################  Output  ############
Class A defined
New from MClass A
Class A definition end
New from A ()
Init from A ()
Object created: A
Class B defined
New from MClass B
Class B definition end
New from B ()
Object created: B

#################  Output  End ############
>From this example , we can see that when we are defining any class ( not
creating object), it call some methods from the metaclass. If I am
returning something from __new__ then it call __init__ of current class
otherwise it skips the calling even when I am creating object. Now suppose
that If I never assigned any metaclass manually then I will not be aware
that something is happening when I am defining the class.

How can I know these internals?
-- 


*With Regards,*
*Deepak Kumar Dixit*


More information about the Tutor mailing list