简体   繁体   English

Python导入问题

[英]Python imports issue

I have a Utilities module which defines a few functions which are repeatedly used and am also adding in some constants. 我有一个实用程序模块,它定义了一些可以重复使用的函数,并且还添加了一些常量。 I'm running into trouble importing these constants though... 我在导入这些常量时遇到了麻烦...

Let's say I'm working in class A, and I have a class in my constants also named A 假设我在A类中工作,并且我的常量中有一个类也称为A

from Utils.Constants import A as DistinctA
class A(object):
    .... Implementation ....
    some_var = DistinctA.SOME_CONSTANT

class Utils(object):
  class Constants(object):
    class A(object):
      SOME_CONSTANT = "Constant"

I'm probably making this too much like Java, so if so just yell / smack my knuckles with a ruler. 我可能使它像Java一样,所以如果这样,只需用尺子大喊/打我的指关节即可。

When I attempt to import that class, I get an error that there is no module named Constants. 当我尝试导入该类时,出现错误,提示没有名为常量的模块。 What's this python newbie missing? python新手缺少什么?

The identifier after 'from' must point to a module; “ from”之后的标识符必须指向模块; you can't refer to a class. 您不能参考课程。 While I'm not qualified to say whether your nested classes are 'pythonic', I have never seen it done like that before. 尽管我没有资格说出您的嵌套类是否为“ pythonic”,但我从未见过如此做过。 I'd be more inclined to create a constants.py module that contains the A class. 我更倾向于创建一个包含A类的constants.py模块。 Then you could do this: 然后,您可以这样做:

from constants import A as DistinctA

If you really want those constants to live inside utils, you could make utils a package: 如果您确实希望这些常量存在于utils中,则可以将utils打包:

utils/
utils/__init__.py
utils/constants.py

Then you can do: 然后,您可以执行以下操作:

from utils.constants import A as DistinctA

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

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