if __name__='__main__':
时间: 2024-02-12 18:01:20 浏览: 86
if __name__ == '__main__'是Python中常用的条件语句,用于判断当前模块是否作为主程序运行。当模块作为主程序运行时,if __name__ == '__main__'的结果为True,而当模块被导入到其他模块中时,if __name__ == '__main__'的结果为False。
下面是一个示例:
```python
# xiaoming.py
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print(self.name, "is running.")
def eat(self):
print(self.name, "is eating.")
def __str__(self):
return "Person: {} - {}".format(self.name, self.age)
if __name__ == '__main__':
xiaoming = Person('小明', 20)
xiaoming.run()
xiaoming.eat()
print(xiaoming)
```
```python
# xiaomei.py
import xiaoming
xiaomei = xiaoming.Person('小美', 45)
xiaomei.run()
xiaomei.eat()
print(xiaomei)
```
在上述示例中,当我们直接运行xiaoming.py时,if __name__ == '__main__'的结果为True,所以其中的代码会被执行。而当我们运行xiaomei.py时,xiaoming.py被导入为一个模块,此时if __name__ == '__main__'的结果为False,所以其中的代码不会被执行。
阅读全文