Using methods defined in __init__.py within the mo

2020-03-09 08:37发布

Suppose I have the following directory structure:

lib\
--__init__.py
--foo.py
--bar.py

Inside foo and bar, there are seperate methods that both need the same method. For instance:

foo:

def method1():
    win()

bar:

def method2(number):
    if number < 0:
        lose()
    else:
        win()

__init__:

def win():
    print "You Win!"

def lose():
    print "You Lose...."

Is there a way to use the win and lose methods within the init.py in the modules respective subfiles, or do I have to create another file within the folder and have foo and bar import that?

标签: python
2条回答
家丑人穷心不美
2楼-- · 2020-03-09 09:03

Yes, just import the __init__.py module (via either an absolute or relative import, it doesn't really matter).

I never like relative imports, so I'd do so with import mypackage in mypackage.foo, which imports the __init__.py just like a relative import does, and then using it there. I also don't like putting anything in __init__.py though generally, so perhaps you should consider the shared common file anyhow.

查看更多
淡お忘
3楼-- · 2020-03-09 09:10

Use relative imports:

from . import win, lose
查看更多
登录 后发表回答