Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have class prototypes (or forward declarations)?

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()  class C():     pass 

Trying to run that, I get NameError: name 'C' is not defined. Fair enough, but is there any way to make it work, or do I have to manually re-order my classes to accommodate? In C++, I can create a class prototype. Does Python have an equivalent?

(I'm actually playing with Django models, but I tried not complicate matters).

like image 593
Mat Avatar asked Feb 07 '09 22:02

Mat


People also ask

Does Python have forward declaration?

In Python, we don't use forward declaration. However, using forward declaration can have various benefits while writing the source code for a Python program.

Does Python have prototype?

Prototype is a creational design pattern that allows cloning objects, even complex ones, without coupling to their specific classes. All prototype classes should have a common interface that makes it possible to copy objects even if their concrete classes are unknown.

What is forward declaration in OOP?

Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program). Example: // Forward Declaration of the sum() void sum(int, int); // Usage of the sum void sum(int a, int b) { // Body }


1 Answers

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?"

like image 190
verveguy Avatar answered Sep 28 '22 17:09

verveguy