What code is executed when class is defined?

When I import a module with a class, what code is executed when this class is first read and the class object is created? Is there a way to influence what happens?


Edit: I understand that my question may be too general ...

I am looking for something lower level that will allow me to do introspection with C ++. I am expanding my C ++ application using Python. I have some classes that are defined in C ++ and exposed in Python. The user can inherit these classes in scripts, and I want them to be able to get information about them when they were first defined.

+4
source share
5 answers

There are many possible things. Simplest:

The contents of the class block are executed upon first reading.

To see this in action, this example:

 class Foo(object): print "bar" def __init__(self): print "baz" 

bar will be printed when importing the module.

If the class has a specific metaclass, the metaclasses __new__ __new__ will be launched after the code class block starts.

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 work as well, this is what I am familiar with.

+5
source

The definition of class A inheriting from B and C is performed: A = type('A', (B, C), m where m is a dictionary containing class members.

You can influence the process by programming a metaclass. There is no shortage of blog posts and related tutorials .

+4
source

You may be interested in metaclasses , which are classes that control the creation of classes.

+3
source

The code in the class definition is executed just like any other code, but any variables created (including function definitions) will be in the context of the class instead of the global one. This means that you can change the class definition dynamically by adding conditional code:

 class A(object): if 1==2: def f(self): print "the world has gone mad" else: def f(self): print "sanity rules" >>> a = A() >>> af() sanity rules >>> 

However, I have never seen this, and I can not think of a reason for this - he feels pretty fearless.

As others have pointed out, there are many other ways to change the behavior of a class, including metaclasses, inheritance, and class decoders.

+2
source

Python is interpreted, so when a Python module is imported, any class code at the module level is run, as well as the metaclasses of these classes - this means that classes will exist.

C ++ compiles: classes already exist when they are imported; There is no way to control how they are created as they are created.

0
source

All Articles