Python class defined in the same file as another class - how do you get access to the one defined later in the file?

后端 未结 5 1799
迷失自我
迷失自我 2021-01-23 02:06

I\'m very new to Python, I figure this question should be easy to answer.

My problem simplified is this...

I have 2 classes in a File class A and class B. Class

相关标签:
5条回答
  • 2021-01-23 02:27
    class A:
        def __init__(self):
            print "In A"
    
    class B:
        def __init__(self):
            a = A()
            print "In B"
    b = B()
    

    I think you want something like that.

    0 讨论(0)
  • 2021-01-23 02:28

    To access B, you must first have defined B.

    If you want to access B when you define A, you need to move it above A in the file.

    If you want to access B when you call methods in A, you don't need to do anything: by the time you call a method of A, the interpreter has executed all the definitions.

    0 讨论(0)
  • 2021-01-23 02:29

    When python finds a class declaration it creates a new scope and executes the code inside the class in this code block. This means that all class variables are instantiated when the class declaration is executed.

    Now, if you have the two classes like:

    class A:
        something = B
    
    class B:
       pass
    

    Python will execute something = B before creating the B class and thus it yields a NameError.

    You can avoid this in a really simple manner:

    class A:
        something = None
    
    class B:
        pass
    
    A.something = B
    
    0 讨论(0)
  • 2021-01-23 02:41

    So the answer was to use qoutes

    B = fields.ForeignKey('api.resources.B', 'B')
    
    0 讨论(0)
  • 2021-01-23 02:52

    A workaround that comes to my mind is to separate the classes into multiple files, so you could have a python package "models" in which you'll have A.py and B.py. Then you avoid the ordering issue

    0 讨论(0)
提交回复
热议问题