Does Python have class prototypes (or forward declarations)?

前端 未结 6 1760
不思量自难忘°
不思量自难忘° 2020-11-28 10:06

I have a series of Python classes in a file. Some classes reference others.

My code is something like this:

class A():
    pass

class B():
    c = C         


        
6条回答
  •  自闭症患者
    2020-11-28 10:12

    Actually, all of the above are great observations about Python, but none of them will solve your problem.

    Django needs to introspect stuff.

    The right way to do what you want is the following:

    class Car(models.Model):
        manufacturer = models.ForeignKey('Manufacturer')
        # ...
    
    class Manufacturer(models.Model):
        # ...
    

    Note the use of the class name as a string rather than the literal class reference. Django offers this alternative to deal with exactly the problem that Python doesn't provide forward declarations.

    This question reminds me of the classic support question that you should always ask any customer with an issue: "What are you really trying to do?"

提交回复
热议问题