0

私はそれがグリーンホーンの質問であることを知っています。しかし。クラスを含む非常に単純なモジュールがあり、そのモジュールを呼び出して別のモジュールから実行したいと考えています。そのようです:

#module a, to be imported

import statements

if __name__ == '__main__':

    class a1:
        def __init__(self, stuff):
            do stuff

        def run_proc():
            do stuff involving 'a1' when called from another module

#Module that I'll run, that imports and uses 'a':
if __name__ == '__main__':

    import a

    a.run_proc()

ただし、他の人には明らかな理由で、属性エラー: 'Module' object has no attribute 'run_proc' Do I need a static method for this class, or to have my run_proc() method within a class, というエラーが表示されます。インスタンスを初期化しますか?

4

1 に答える 1

4

移動

if __name__ == '__main__':

モジュール a でファイルの最後にパスまたはいくつかのテスト コードを追加します。

あなたの問題は次のとおりです。

  1. の範囲内のものはすべてif __name__ == '__main__':、最上位ファイルでのみ考慮されます。
  2. クラスを定義していますが、クラス インスタンスを作成していません。

モジュール a、インポートする

import statements

class a1:
    def __init__(self, stuff):
        do stuff

    def run_proc():
        #do stuff involving 'a1' when called from another module


if __name__ == '__main__':
    pass # Replace with test code!

「a」をインポートして使用する、実行するモジュール:

import a
def do_a():
    A = a.a1()   # Create an instance
    A.run_proc() # Use it

if __name__ == '__main__':
   do_a()
于 2013-08-06T04:55:01.597 に答える