-1

mod = importlib.import_module(str)fromSample2.pyとモジュールを使用してモジュールを呼び出そうとしています

functionPlayAround_Play.pyのみが含まれている場合、正常に動作しています。その関数にクラスを含めた場合

うまくいきません。エラーを取得するTypeError: this constructor takes no arguments

sample2.py のコード

import importlib
def calling():
      str="PlayAround_Play" 
      a=10
      b=20
      c=30
      mod = importlib.import_module(str)
      getattr(mod,str)(a, b, c)    

calling()

PlayAround_Play.py のコード

class PlayAround_Play():
        def PlayAround_Play(self, a, b, c):
              d=a+b+c
              print d

を使用してそのクラスを呼び出す方法を教えてくださいimportlib

4

1 に答える 1

1

クラスを間違って、正しい方法で呼び出しています:

inst = getattr(mod, strs)()   #creates an instance of the class
inst.PlayAround_Play(a, b, c) #call `PlayAround_Play` method on the instance.

出力:

60

コードをうまく機能させる__init__には、クラスで次のように定義します。

class PlayAround_Play():

    def __init__(self, a, b, c):
        d = a+b+c
        print d

今:

getattr(mod, strs)(a, b, c)
#prints 60

読んだ:

于 2013-11-06T09:26:10.870 に答える