我在这里和其他地方询问过相同的东西,但是他们给出的答案要么不起作用,要么我误解了答案。导入自定义目录
我正在使用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.
”它增加了字CityNames
和city_names
下一个红色下划线。
当我添加.
之前CityNames
(from .CityNames import *
),错误消失,但代码停止工作给我下面的错误代码,当我尝试运行它:也
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
添加到目录。我不确定这是为什么,或者为什么我会添加它。当我添加它时,它似乎没有什么区别。我是否需要在文件中添加内容或将其保留为空?
它适用于我;你是否尝试在PyCharm之外运行它? – dashiell
您应该阅读[** _第十亿次_ **的相对导入](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time)。 – martineau
https://stackoverflow.com/questions/21236824/unresolved-reference-issue-in-pycharm也许这会对它产生一些影响 – dashiell