In python, the code in the class runs when the class loads.
Now what the hell does that mean ?; -)
Consider the following code:
class x: print "hello" def __init__(self): print "hello again"
When loading a module containing the code, python will print hello . Whenever you create x , python will print hello again .
You can think of def __init__(self): ... as the equivalent with __init__ = lambda self: ... , except that none of the python lambda restrictions apply. That is, def is an assignment that can explain why methods are run outside the code, but not internal methods.
When your code says
class X(models.Model): creator = Registry() creator.register(Y)
You access Y when the module is loaded, before Y matters. You can think of class X as an assignment (but I can't remember the syntax for creating anonymous classes outside the field, maybe this is a type call?)
What you can do is:
class X(models.Model): pass class Y(models.Model): foo = something_that_uses_(X) X.bar = something_which_uses(Y)
That is, create attributes of class x , which will create a link Y after Y Or vice versa: first create Y , then x , then Y attributes, which depend on x , if it's easier.
Hope this helps :)
Jonas kölker
source share