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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With