如何在Python中调用一个函数

时间:2015-04-21 05:59:58

标签: python

这里我想在整个程序中只调用一次Web服务功能。 怎么做到这一点任何人都建议我

import sys,os

def web_service(macid):
        # do something

if "__name__" = "__main__" :
      web_service(macid)

2 个答案:

答案 0 :(得分:1)

这就是我想要的:

i_run_once_has_been_run = False

def i_run_once(macid):
    global i_run_once_has_been_run

    if i_run_once_has_been_run:
        return

    # do something

    i_run_once_has_been_run = True

@Voulstein的装饰功能也会起作用,甚至可能会更加pythonic - 但对我来说似乎有点矫枉过正。

答案 1 :(得分:0)

使用class,

class CallOnce(object):
    called = False

    def web_service(cls, macid):
        if cls.called:
            print "already called"
            return
        else:
            # do stuff
            print "called once"
            cls.called = True
            return


macid = "123"
call_once_object = CallOnce()
call_once_object.web_service(macid)
call_once_object.web_service(macid)
call_once_object.web_service(macid)

结果是,

I have no name!@sla-334:~/stack_o$ python once.py 
called once
already called
already called