簡體   English   中英

將main.py導入另一個模塊(包含在同一目錄中)

[英]Importing main.py into another module (contained in the same directory)

如何將類從main.py導入到同一目錄中的另一個文件中?

文件結構:

Project
    |-- main.py
    |-- first_file.py
    |-- second_file.py

main.py

class ClassX():
    def random1(self):
        ....
        return stuff

    def get(self):
        class_x_stuff = self.random1()
        print class_x_stuff

app = webapp2.WSGIApplication([
    ('/classw', ClassW),
    ('/classx', ClassX)
], debug=True)

first_file.py

import main

checkpoint = main.ClassX()
print checkout

輸出:

AttributeError: 'module' object has no attribute 'ClassX'

我使用的資源:

  1. 如何在同一目錄或子目錄中導入類?
  2. AttributeError:“模塊”對象沒有屬性

我可以將first_file.py導入main.py以及second_file.py 但是我無法將main.py導入其他文件。

重命名main.py文件(例如proj_main.py )會導致錯誤:

Traceback (most recent call last):
File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
  handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
  handler, path, err = LoadObject(self._handler)
File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
  obj = __import__(path[0])

ImportError: No module named main

我有什么選擇? 我該如何解決這個問題?

編輯:

完整回溯:

INFO     2017-10-02 22:10:21,744 dispatcher.py:226] Starting module "default" running at: http://localhost:7070
INFO     2017-10-02 22:10:21,747 admin_server.py:116] Starting admin server at: http://localhost:8000
ERROR    2017-10-02 22:10:24,017 wsgi.py:263] 
Traceback (most recent call last):
  File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
  File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
  File "/Users/mycomputer/Documents/project_folder/main.py", line 34, in <module>
from first_file import ClassY
  File "/Users/mycomputer/Documents/project_folder/first_file.py", line 20, in <module>
    checkpoint = main.ClassX()
AttributeError: 'module' object has no attribute ‘ClassX’
INFO     2017-10-02 22:10:24,023 module.py:832] default: "GET / HTTP/1.1" 500 -

問題是我遇到了循環依賴

File "/Users/mycomputer/Documents/project_folder/main.py", line 34, in <module>
from first_file import ClassY

請注意, main.py是從first_file導入的,然后first_file是從main.py導入的,這導致了循環導入 main.py

解:

first_file.py

import second_file

checkpoint = second_file.class_x()
    print checkout

second_file.py

import main

def class_x():
    item = main.ClassX()
    return item

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM