3

次のような構造の template という名前のフォルダーからインポートしようとしています

controller/
          /__init__.py
          /login.py # <- I'm here
template/
        /__init__.py # from template import *
        /template.py # contains class Template

pythonは必要なクラスを確認できるようですが、インポートに失敗します。これはlogin.pyコードです

import webapp2

import template

class Login(webapp2.RequestHandler):
#class Login(template.Template):

    def get(self):
        self.response.out.write(dir(template))

版画

['Template', 'Users', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', 'jinja2', 'os', 'template', 'urllib', 'webapp2']

輸入ラインの切り替え

import webapp2

import template

#class Login(webapp2.RequestHandler):
class Login(template.Template):

    def get(self):
    self.response.out.write(dir(template))

版画

class Login(template.Template):
AttributeError: 'module' object has no attribute 'Template'

私は何を間違っていますか?ありがとう

編集: index という名前の別のフォルダーを作成しました

index/
     /__init__.py # from index import *
     /index.py # class Index
     /index.html

index.py 内のコードは

from template import Template
class Index(Template):
    def get(self):
        self.render("/index/index.html")

このコードはエラーなしで機能しましたが、1 つのインデックス コントローラー フォルダーでエラーが発生しました

4

1 に答える 1

5

問題は、いつtemplate/__init__.py行うかということです。

from template import *

思った場所からインポートするのではなく、それ自体からすべてをインポートします。これは、「template」というフォルダに「template」__init__.pyというモジュールが定義されているためです。このフォルダは、「template」とも呼ばれるその中のモジュールよりも優先されます。内部モジュールが必要であることをPythonに明示的に伝える必要があります。これは、次のように実行できます。

from .template import *
于 2012-07-28T08:28:12.703 に答える