简体   繁体   English

在Python中,如何在同一文件夹中定义的类中的__init__.py中调用函数

[英]in Python how do call functions in __init__.py in a class defined in the same folder

I have a python package 我有一个python包

- my_package
  - __init__.py
       # inside
       def getSingleton()  # gets an instance of an object in the package
  - AClass.py
       # inside
       class AClass:
           ...
           def instanceMathod(self,arg):
              singleton = (parent package).getSingleton()

I want to use the module "static" functions from within class instances from the module ie: reference the parent module from a contained class instance? 我想从模块的类实例中使用模块的“静态”功能,即:从包含的类实例中引用父模块? Can one do this? 可以这样做吗? Is there a better way? 有没有更好的办法? Much works well as the singleton will be destroyed when the containing module is destroyed when all importing modules have been destroyed. 当所有导入模块都被销毁时,如果包含模块被销毁,则单例将被销毁,因此效果很好。 I'm using python3 我正在使用python3

Use: 采用:

def instanceMethod(self,arg):
    from . import getSingleton
    singleton = getSingleton()

Here we are deferring the import until the method is called, rather than importing at global scope, in case mypackage.__init__ is also importing AClass 在这里,我们将导入推迟到调用该方法之前,而不是在全局范围内导入,以防mypackage.__init__也在导入AClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM