导入自定义目录

时间:2017-08-01 17:12:12

标签: python python-3.x import

我在这里和其他地方看过一些问题同样的问题,但他们给出的答案要么不起作用,要么我误解了答案。

我正在使用Python 3.我需要将CityNames.py导入Cities.py

我有以下目录:

CityBorders
  | Cities.py
  | CityNames.py

以及文件中的以下代码:

Cities.py

from CityNames import *
from random import choice


class City:
    def __init__(self):
        self.set_name()

    def set_name(self):
        if hasattr(self, 'name'):
            city_names[self.name] = None

        self.name = choice([n for n, c in city_names.items() if c is None])
        city_names[self.name] = self


def get_cities(count):
    return [City() for _ in range(min(count, len(city_names)))]


cities = get_cities(20)
print([c.name for c in cities])

CityNames.py

city_names = {
    "Macclesfield": None,
    "Blue Field": None,
    "Farnworth": None,
    "Foolshope": None,
    "Waterrun": None,
    "Murtovaara": None,
    "Nancledra": None,
    "Aeberuthey": None,
    .
    .
    .
    "Middlesbrough": None,
    "Balerno": None
}

使用此代码,程序似乎运行正常,但PyCharm显示致命错误,“This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.”它在单词CityNamescity_names下添加了一个红色下划线。

当我在.CityNames)之前添加from .CityNames import *时,错误就会消失,但是当我尝试运行时代码停止工作时会给我以下错误代码:< / p>

Traceback (most recent call last):
  File "S:/Makai/Projects/Artifitial Art/CityBorders/Cities.py", line 1, in <module>
    from .CityNames import *
ModuleNotFoundError: No module named '__main__.CityNames'; '__main__' is not a package

此外,在查看其他人提出的问题时,他们中的许多人都在谈论将__init__.py添加到目录中。我不确定为什么会这样或为什么我会添加它。当我添加它时,它似乎没有什么区别。我是否需要在文件中包含某些内容或将其留空?

1 个答案:

答案 0 :(得分:1)

我也使用PyCharm,所以

怎么样:

from . import CityNames.city_names as cn

在我使用的django项目中:

from . import views

它完美无缺!