导入单个类并使用该类,得到了意料之外的结果
首先我编写了一个名为“练习9_1.py”的模块,如下
class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.name=restaurant_name
self.type=cuisine_type
print(self.name)
print(self.type)
def describe_restaurant(self):
print(f"The name of the restaurant is {self.name.title()}.")
print(f"The cuisine type of it is {self.type.title()}.")
def open_restaurant(self):
print("The restaurant is opening!")
my_restaurant=Restaurant('gugio', 'japanese food')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
your_restaurant=Restaurant('lucio', 'chinese food')
your_restaurant.describe_restaurant()
your_restaurant.open_restaurant()
his_restaurant=Restaurant('fucci', 'indian food')
his_restaurant.describe_restaurant()
his_restaurant.open_restaurant()
然后我执行了如下代码
from 练习9_1 import Restaurant
my_restaurant=Restaurant('gugio', 'japanese food')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
结果是:
gugio
japanese food
The name of the restaurant is Gugio.
The cuisine type of it is Japanese Food.
The restaurant is opening!
lucio
chinese food
The name of the restaurant is Lucio.
The cuisine type of it is Chinese Food.
The restaurant is opening!
fucci
indian food
The name of the restaurant is Fucci.
The cuisine type of it is Indian Food.
The restaurant is opening!
gugio
japanese food
The name of the restaurant is Gugio.
The cuisine type of it is Japanese Food.
The restaurant is opening!
我预期中是只会执行下面这部分,为什么还会执行练习9_1模块中Restaurant类后的全部程式码?
my_restaurant=Restaurant('gugio', 'japanese food')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
关于 LearnKu
模块可以包含可执行的语句以及函数定义, 这些语句用于初始化模块. 它们仅在模块第一次在import 语句中被导入时才执行. (当文件被当作脚本运行时,它们也会执行. ). 即使你只导入一部份, 也是要初始化模块.
如果你不想在初始化时, 执行这些语句, 就必须予以区分.