简体   繁体   中英

How to reference another nested class from within nested class

I have the following nested structure:

from peewee import *

class Parent:
    ...
    class A:
        name = TextField()

    class B:
        from_A = ForeignKeyField(A)

I am trying to reference class A within a ForeignKeyField within class B, but both A and Parent.A return a name not found error. What is the proper way to reference class A from within class B? Is this possible?

At the time of definition of class B, class Parent is not fully defined so it cannot be used: at definition time, you can only use:

  • global variables
  • variables belonging to the element being defined

But you have no access to variables defined in an enclosing block be them classes or not.

So you are left with only two options:

  • define class B outside of Parent
  • initialize the element at run time after everything has been defined (in that sense, run time starts immediately the end of the class Parent block`):

     class Parent: ... class A: name = TextField() class B: ... Parent.B.from_A = ForeignKeyField(Parent.A) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM