Skip to main content
 首页 » 编程设计

python之从父文件访问资源

2025年05月04日10lonelyxmas

# models/__init__.py 
 
from shared.cache import Cache 
 
class modelA(): 
    pass 
class modelB(): 
    pass 
class modelC(): 
    pass 
 
# shared/cache.py 
 
class Cache: 
    def methodA(): 
        modelA.SomeStaticMethod() 

基本上我需要的是从 Cache 类内部访问 modelA。 如果我尝试从 cache.py 导入模型,我会因循环引用错误而收到错误消息。

我知道这看起来有点奇怪,但这是一个非常具体的问题。 有办法吗?

请您参考如下方法:

您通常会重组文件,以免出现循环引用错误。

简单地回答你的问题,通常被视为一种解决方法,你可以按需导入 Cache,仅在 models/__init__.py 的函数中使用它。在这种情况下,这可能是不可能的,尤其是当 Cache 被用作模块级别的装饰器时。

另见 this问题。