这是被调用的模块,我想调用其中的describe_restaurant()。
class Restaurant():
def __init__(self, name, type):
self.restaurant_name = name
self.cuisine_type = type
def describe_restaurant(self):
print("The name of the restaurant is "
+ self.restaurant_name.title() + ".")
print("The cuisine type of the restaurant is "
+ self.cuisine_type.title() + ".")
def open_restaurant(self):
print(self.restaurant_name.title()
+ " is open now.")
restaurant = Restaurant('panda','chinese food')
res2 = Restaurant('tuesday','mexico food')
res3 = Restaurant('thai','thai food')
print(restaurant.restaurant_name)
print(restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
res2.describe_restaurant()
res3.describe_restaurant()
这是进行调用的模块
from restaurant import Restaurant
res = Restaurant('panda','chinese food')
res.describe_restaurant()
我想得到的输出是
The name of the restaurant is Panda.
The cuisine type of the restaurant is Chinese Food.
而实际输出是
panda
chinese food
The name of the restaurant is Panda.
The cuisine type of the restaurant is Chinese Food.
Panda is open now.
The name of the restaurant is Tuesday.
The cuisine type of the restaurant is Mexico Food.
The name of the restaurant is Thai.
The cuisine type of the restaurant is Thai Food.
The name of the restaurant is Panda.
The cuisine type of the restaurant is Chinese Food.
类中的代码写的太多了,类中16行以后的代码全部删掉。
模块中存储的应该是一个或多个类,同样的,调用时也是调用一个或多个类。16行以后的代码,不属于类,放在调用代码中更合适。
调用代码没问题,之所以输出结果多于预期,是因为类中执行了调用,在后面调用类时同时也执行了类中的调用。把类中多余的代码删掉即可。
class Restaurant():
def __init__(self, name, type):
self.restaurant_name = name
self.cuisine_type = type
def describe_restaurant(self):
print("The name of the restaurant is "
+ self.restaurant_name.title() + ".")
print("The cuisine type of the restaurant is "
+ self.cuisine_type.title() + ".")
def open_restaurant(self):
print(self.restaurant_name.title()
+ " is open now.")
调用
from restaurant import Restaurant
res = Restaurant('panda','chinese food')
res.describe_restaurant()
运行结果
>>>The name of the restaurant is Panda.
>>>The cuisine type of the restaurant is Chinese Food.
在这些前面加一个 if
if __name__ == '__main__':
restaurant = Restaurant('panda', 'chinese food')
res2 = Restaurant('tuesday', 'mexico food')
res3 = Restaurant('thai', 'thai food')
print(restaurant.restaurant_name)
print(restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
res2.describe_restaurant()
res3.describe_restaurant()
只需要类定义那部分,其他都删掉就行