有人能给我一个解决方案吗
dosomething()
def dosomething():
print do something
我不希望我的方法定义在文件的顶部,有办法解决这个问题吗?
有人能给我一个解决方案吗
dosomething()
def dosomething():
print do something
我不希望我的方法定义在文件的顶部,有办法解决这个问题吗?
“标准”方法是在文件顶部的main
函数内执行操作,然后在底部调用main()
。例如。
def main():
print doing stuff
foo()
bar()
def foo():
print inside foo
def bar():
print inside bar
if __name__ == __main__ :
main()
ifif__name__==__main__:
部分确保在文件导入另一个python程序时不会调用main()
,而仅在文件直接运行时调用。
当然,“main”并不意味着什么。。。(不过,__main__
确实如此!)这是一个psuedo约定,但您也可以将其称为do_stuff
,然后在底部设置if __name__==__main__:do_stuff()
。
编辑:您可能还想查看Guido关于编写main
s的建议。此外,Daenyth提出了一个很好的观点(并击败了我的回答):你应该这样做的原因不是“标准的”,甚至不是因为它允许你在“main”代码下面定义函数。你应该这么做的原因是它鼓励你编写模块化和可重用的代码。
除了将dosomething
的定义添加到单独的文件中并导入外:
from my_module import dosomething
dosomething()
我不相信还有别的办法。。。但我可能错了。
Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...
I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...
Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...
Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...
I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...
Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...
Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...
I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...