2014-05-15 85 views
1

我有以下python代码(有点简化,但它确实犯了同样的错误)。将类方法传递给python中的类方法的问题

class traffic(object): 
    def __init__(self, testObj): 
     try: 
      <do something> 
     except AssertionError: 
      sys.exit (1) 
    def add(self, phase='TEST'): 
     <do something> 
    def check(self, phase='TEST'): 
     <do something> 

class testcase(object): 
    def __init__(self): 
     try: 
      <do something> 
     except AssertionError: 
      sys.exit (1) 
    def addSeqPost(self, cmdObj): 
     print "add Seq. for POST" 
     cmdObj(phase='POST') 

tc = testcase() 
test = traffic(tc) 
tc.addSeqPost(test.add()) 

我得到以下类型错误:

Traceback (most recent call last): 
    File "test.py", line 25, in <module> 
    tc.addSeqPost(test.add()) 
    File "test.py", line 20, in addSeqPost 
    cmdObj(phase='POST') 
TypeError: 'NoneType' object is not callable 

如果我改变我的代码,它的工作原理,但它不是我想什么:

def addSeqPost(self, cmdObj): 
     print "add Seq. for POST" 
     cmdObj.add(phase='POST') 

tc.addSeqPost(test()) 

我想使它更通用,因为test()可以有更多的方法,我想传入tc.addSeqPost(),如tc.addSeqPost(test.check())。

谢谢你。为你的时间和帮助

在alKid的帮助下。

还有一个问题,如果我想通过一个参数test.check(duration = 5)呢?尽快我这样做,我得到了相同TypeError ...但我不想/需要返回任何东西从添加!

例子:

... 
    def check(self, phase='TEST', duration=0): 
     <do something> 

tc = testcase() 
test = traffic(tc) 
tc.addSeqPost(test.add) 
tc.addSeqPost(test.check(duration=5)) 

回答

0

test.add()不会返回的功能,它运行的功能,并还给返回值。由于add不返回任何内容,传递的对象是None

tc = testcase() 
test = traffic(tc) 
tc.addSeqPost(test.add) 

此外,请记住test.add需要参数。 selfphase。你需要通过他们两个。

def addSeqPost(self, cmdObj): 
    print "add Seq. for POST" 
    cmdObj(self, phase='POST') #pass an instance of `testcase` to the function. 

传递另一个类的实例可能不是你想要做的,但它只是一个例子。

希望这会有所帮助!

+0

你是完全正确的,这个作品!我只需要使用test.add,完美!再次感谢 – FotisK

+0

@ user3458191如果这个答案对您有帮助,请在接受按钮上勾选,在投票按钮下方:D – aIKid

+0

还有一个问题,如果我想通过test.add(持续时间= 5)传递一个参数会怎样?尽快我这样做,我得到了相同TypeError ...但我不想/需要返回任何东西从添加!然后通过两个参数 – FotisK

相关问题