Python observer pattern

I'm new to python, but I ran into a problem while 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 does not work because it says X is undefined. Several things are possible:

A) There is a way to refer to the current class (not an instance, but a class object).

B) You cannot even run code outside the method. (I thought this could work almost like a static constructor - it will just run once).

+4
source share
2 answers

There is nothing wrong with the class definition:

 class X(object): print("Loading X") 

However, you cannot refer to X because it is not yet fully defined.

+4
source

In python, the code defined in the block of the class is executed, and only then , depending on various things - for example, what was defined in this block - a class is created. Therefore, if you want to associate one class with another, you must write:

 class X(models.Model): a = models.ForeignKey(Voter) b = models.CharField(max_length=200) # Register Y.register(X) 

And this behavior is not related to django.

+5
source

Source: https://habr.com/ru/post/1286775/


All Articles