我在這裏和其他地方詢問過相同的東西,但是他們給出的答案要麼不起作用,要麼我誤解了答案。導入自定義目錄
我正在使用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