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

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日

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)