簡體   English   中英

Python 類與另一個類在同一個文件中定義 - 如何訪問文件中稍后定義的類?

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

我是 Python 的新手,我認為這個問題應該很容易回答。

我的問題簡化是這樣的......

我在文件類 A 和類 B 中有 2 個類。首先在文件中定義類 A,然后再定義類 B。

class A
    ...

class B
    ...

我如何使用 A 類訪問 B 類?

class A
    something = B

class B
    somethingElse = A

這是我要修復的實際代碼

class FirstResource(_ModelResource):
    class Meta(_Meta):
        queryset = First.objects.all()
        resource_name = 'first'
        allowed_methods = ['get','put']

        filtering = {
            'a': ALL_WITH_RELATIONS,
            'b': ALL_WITH_RELATIONS,
            'c': ALL_WITH_RELATIONS,
        }

        ordering = ['apt']

    # this is the line that would fix everything
    second = fields.ForeignKey(SecondResource, 'second', null=True, blank=True, default=None, full=True) 

    ...

 class SecondResource(_ModelResource):
    class Meta(_Meta):
        queryset = Second.objects.all()
        resource_name = 'second'
        execute_methods = ['get', 'post']
        filtering = {
            'name': ['exact'],
            'leader': ['exact'],
        }   

    super = fields.ForeignKey(FirstResource, 'super', null=True, blank=True, default=None, full=True)
    leader = fields.ForeignKey(FirstResource, 'leader', null=True, blank=True, default=None, full=True)

    ...

由於沒有在 Python 中預先聲明,我真的不確定如何解決這個問題。 models.py 中的 First 有一個外鍵 Second,Second 有 2 個外鍵 First。

將 A 移到 B 下方並不能解決問題,因為 B 也需要 A。我沒有編寫代碼,我只是想修復它 - 當我為資源執行“獲取”時,我需要返回“第二個”外鍵在兩個班級。

所以答案是使用 qoutes

B = fields.ForeignKey('api.resources.B', 'B')

要訪問B ,您必須先定義B

如果要在定義A時訪問B ,則需要將其移動到文件中A的上方。

如果您想在調用A中的方法時訪問B ,則無需執行任何操作:在您調用A的方法時,解釋器已執行所有定義。

當 python 找到一個類聲明時,它會創建一個新的作用域並在此代碼塊中執行類內的代碼。 這意味着所有類變量在執行類聲明時被實例化。

現在,如果您有兩個類,例如:

class A:
    something = B

class B:
   pass

Python 將在創建B之前執行something = B ,因此它會產生一個NameError

您可以通過一種非常簡單的方式避免這種情況:

class A:
    something = None

class B:
    pass

A.something = B
class A:
    def __init__(self):
        print "In A"

class B:
    def __init__(self):
        a = A()
        print "In B"
b = B()

我想你想要那樣的東西。

我想到的一個解決方法是將類分成多個文件,這樣您就可以擁有一個 python 包“模型”,其中包含 A.py 和 B.py。 然后你避免訂購問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM