怎么if __name__ == "__main__":办?
# Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while True:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
Run Code Online (Sandbox Code Playgroud) 我是Python新手,但我有其他OOPS语言的经验.我的课程没有解释python中的主要方法.
请告诉我python中main方法的工作原理?我很困惑,因为我试图将它与Java进行比较.
def main():
# display some lines
if __name__ == "__main__": main()
Run Code Online (Sandbox Code Playgroud)
主要如何执行,为什么我需要这个奇怪if的执行main.当我删除时,我的代码终止而没有输出if.
最小的代码 -
class AnimalActions:
def quack(self): return self.strings['quack']
def bark(self): return self.strings['bark']
class Duck(AnimalActions):
strings = dict(
quack = "Quaaaaak!",
bark = "The duck cannot bark.",
)
class Dog(AnimalActions):
strings = dict(
quack = "The dog cannot quack.",
bark = "Arf!",
)
def in_the_doghouse(dog):
print(dog.bark())
def in_the_forest(duck):
print(duck.quack())
def main():
donald = Duck()
fido = Dog()
print("- In the forest:") …Run Code Online (Sandbox Code Playgroud)