Skip to main content
 首页 » 编程设计

Python 类与另一个类在同一个文件中定义之如何访问文件中稍后定义的类

2025年05月04日15youxin

我是 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')