Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python observer pattern

Tags:

python

django

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).

like image 419
Daniel Avatar asked Jan 24 '23 11:01

Daniel


2 Answers

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.

like image 102
liori Avatar answered Feb 05 '23 07:02

liori


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.

like image 24
Matthew Flaschen Avatar answered Feb 05 '23 09:02

Matthew Flaschen