wo_squirrel 2021-08-13 15:52 采纳率: 100%
浏览 44
已结题

Python,只想调用类中的一个方法,但是其他方法也执行了

这是被调用的模块,我想调用其中的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.

  • 写回答

3条回答 默认 最新

  • 漫夜长空 2021-08-13 21:58
    关注

    类中的代码写的太多了,类中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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 8月22日
  • 已采纳回答 8月14日
  • 创建了问题 8月13日