【问题标题】:Python class defined in the same file as another class - how do you get access to the one defined later in the file?与另一个类在同一个文件中定义的 Python 类 - 如何访问文件中稍后定义的类?
【发布时间】:2020-08-09 18:47:54
【问题描述】:

我对 Python 很陌生,我认为这个问题应该很容易回答。

我的问题简化后是这样的......

我在 File 类 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 有一个 ForeignKey 为 Second,Second 有 2 个 Foreign Key 为 First。

将 A 移到 B 下面并不能解决问题,因为 B 也需要 A。我没有编写代码,我只是想修复它 - 当我执行“获取”时,我需要返回“第二个”外键用于两个类中的资源。

【问题讨论】:

  • 不能将 B 类移到 A 类之上
  • 为什么?你能告诉我们实际的代码吗?
  • 已编辑,以便您可以看到更多细节 larsks

标签: python django django-models


【解决方案1】:

要访问B,您必须首先定义B

如果要在定义 A 时访问B,则需要在文件中将其移至A 上方。

如果你想在你调用A中的方法时访问B,你不需要做任何事情:当你调用A的方法时,解释器已执行所有定义。

【讨论】:

  • 那么我如何强制它在返回'get'之前调用一个方法?
【解决方案2】:

所以答案是使用 qoutes

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

【讨论】:

  • 请注意,此功能是 Django 特有的,在普通 Python 中不起作用。这是因为 Django 将在 INSTALLED_APPS 中的应用程序中搜索正确的包。因此,此答案并不能解决您提出的简化问题。
【解决方案3】:

当 python 找到一个类声明时,它会创建一个新范围并执行此代码块中类内的代码。这意味着在执行类声明时会实例化所有类变量。

现在,如果您有两个类,例如:

class A:
    something = B

class B:
   pass

Python 将在创建B 类之前执行something = B ,从而生成NameError

您可以通过非常简单的方式避免这种情况:

class A:
    something = None

class B:
    pass

A.something = B

【讨论】:

    【解决方案4】:
    class A:
        def __init__(self):
            print "In A"
    
    class B:
        def __init__(self):
            a = A()
            print "In B"
    b = B()
    

    我想你想要这样的东西。

    【讨论】:

      【解决方案5】:

      我想到的一种解决方法是将类分成多个文件,这样您就可以拥有一个 python 包“模型”,其中包含 A.py 和 B.py。然后你就避免了订购问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 2012-09-18
        • 2021-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多