简体   繁体   English

将类方法传递给python中的类方法的问题

[英]Issue with passing class method into a class method in python

i have following python code (a bit simplified, but it did make the same error). 我有以下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())

I get the below TypeError: 我得到以下TypeError:

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

If i change my code to, it works, but it is not what i would like: 如果我将代码更改为它,则可以工作,但这不是我想要的:

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

tc.addSeqPost(test())

I would like to make it more general because the test() could have more methods that i would like to pass into tc.addSeqPost(), like tc.addSeqPost(test.check()). 我想使它更通用,因为test()可以有更多我想传递给tc.addSeqPost()的方法,例如tc.addSeqPost(test.check())。

Thanks in adv. 感谢在广告中。 for your time and help 为您的时间和帮助

After the help from alKid. 经过alKid的帮助。

One issue remains, what if i want to pass a parameter with test.check(duration=5)? 一个问题仍然存在,如果我想通过test.check(duration = 5)传递参数怎么办? As soon i do that i got the same TypeError...But i don't want/need to return anything from add!!! 我马上就得到了相同的TypeError ...但是我不想/需要从add返回任何东西!!!

Example: 例:

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

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

test.add() will not return the function, it runs the function and gives back the returned value. test.add()将不会返回该函数,它将运行该函数并返回返回的值。 Since add doesn't return anything, the object passed is None . 由于add不返回任何内容,因此传递的对象为None

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

Also, remember that test.add needs two arguments. 另外,请记住, test.add需要两个参数。 self and phase . selfphase You need to pass both of them. 您需要同时通过它们。

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

Passing another class's instance might not be what you want to do, but it's just an example. 传递另一个类的实例可能不是您想要执行的操作,但这只是一个示例。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM