我可以引用以其包为前缀的Python类吗?

时间:2019-05-22 17:43:38

标签: python

我在包中有一些Python模块,例如:

root/
  airplane/
    __init__.py
    propeller.py # defines class Propeller
    engine.py    # defines class Engine
  boat/
    __init__.py
    engine.py    # defines class Engine

我想引用以包开头的类构造函数(或其他类/静态方法),以避免产生歧义:

airplaneEngine = airplane.Engine('4 cylinder')
boatEngine     = boat.Engine('6 cylinder')
if boatEngine.isFasterThan(airplaneEngine): print('Boat wins!')

但是我无法使导入正常工作。

from airplane import engine
airplaneEngine = airplane.Engine('4 cylinder') 
# NameError: name 'airplane' is not defined

from airplane.engine import Engine
airplaneEngine = airplane.Engine('4 cylinder') 
# NameError: name 'airplane' is not defined

我知道我可以做到:

from airplane.engine import Engine as AirplaneEngine
airplaneEngine = AirplaneEngine('4 cylinder') 

或者这个:

root/
  airplane.py # defines class Propeller & class Engine
  boat.py     # defines class Engine

import airplane
airplaneEngine = airplane.Engine('4 cylinder')

但是我不喜欢这些解决方案。有没有办法引用包前缀的static / class方法?

1 个答案:

答案 0 :(得分:1)

from airplane import engine
airplaneEngine = airplane.Engine('4 cylinder') 
# NameError: name 'airplane' is not defined

from airplane.engine import Engine
airplaneEngine = airplane.Engine('4 cylinder') 
# NameError: name 'airplane' is not defined

应该是

from airplane import engine
airplaneEngine = engine.Engine('4 cylinder') 

from airplane.engine import Engine
airplaneEngine = Engine('4 cylinder') 

在第一次尝试中,您正在导入engine文件,并且可以引用其中的类。您尚未导入airplane,仅导入了该文件夹中的文件。

在第二次尝试中,您正在导入Engine类,但同样没有导入airplane。此外,Engine类不属于airplane,它位于engine.py