我是 Python 的新手,但我有其他面向对象编程语言的经验。我的课程没有解释 Python 中的主要方法。
请告诉我主方法在 python 中是如何工作的?我很困惑,因为我试图将它与 Java 进行比较。
def main():
# display some lines
if __name__ == "__main__": main()
Main 是如何执行的,为什么我需要这个奇怪的 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:")
for o in ( donald, fido ):
in_the_forest(o)
print("- In the doghouse:")
for o in ( donald, fido ):
in_the_doghouse(o)
if __name__ == "__main__": main()