Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What code is executed when a class is being defined?

When I import a module that has a class, what code is executed when that class is first read and the class object created? Is there any way I can influence what happens?


Edit: I realize my question might be a bit too general...

I'm looking for something more low-level which will allow me to do introspection from C++. I extend my C++ application with Python. I have some classes that are defined in C++ and exposed in Python. The user can inherit from these classes in the scripts and I want to be able to grab details about them when they are first defined.

like image 303
Paul Manta Avatar asked Dec 09 '22 05:12

Paul Manta


1 Answers

Many possible things can happen. The most basic:

The contents of the class block are executed when the it is first read.

To see this in action, this example:

class Foo(object):
    print "bar"

    def __init__(self):
        print "baz"

Will print bar when the module is imported.

If a class has a metaclass defined, the metaclasses __new__ function will run after the classes block of code is run.

Example:

class MyMeta(type):
    def __new__(mcs, name, bases, kwargs):
        print "I'm the metaclass, just checking in."
        return type.__new__(mcs, name, bases, kwargs)


class Foo(object):
    __metaclass__ = MyMeta

    print "I'm the Foo class"

Output:

I'm the Foo class
I'm the metaclass, just checking in.

I'm sure other bits can run as well, these are just what I am familiar with.

like image 174
Adam Wagner Avatar answered Dec 24 '22 23:12

Adam Wagner