I'm new to python but I've run into a hitch when trying to implement a variation of the observer pattern.
class X(models.Model):
a = models.ForeignKey(Voter)
b = models.CharField(max_length=200)
# Register
Y.register(X)
This doesn't seem to work because it says X is not defined. A couple of things are possible:
A) There is a way to refer to the current class (not the instance, but the class object).
B) You can't even run code outside a method. (I thought this may work almost like a static constructor - it would just get run once).
In python, code defined in a class block is executed and only then, depending on various things---like what has been defined in this block---a class is created. So if you want to relate one class with another, you'd write:
class X(models.Model):
a = models.ForeignKey(Voter)
b = models.CharField(max_length=200)
# Register
Y.register(X)
And this behaviour is not related to django.
There is nothing wrong with running (limited) code in the class definition:
class X(object):
print("Loading X")
However, you can not refer to X because it is not yet fully defined.
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