Python 类的练习

练习任务:创建一个名为restaurant的类,其方法__init__()设置连个属性:restaurant_name和cuisine_type。创建一个名为describe_restaurant()的方法和一个名为open_restaurant()的方法,其中前者打印前述两项信息,而后者打印一条信息,指出餐厅正在营业。

根据这个类创建一个实例,分别打印其两个属性,再调用前述两个方法。

class Restaurant():
    #定义一个类,描述餐馆
    
    def __init__(self, restaurant_name, cuisine_type):
        """定义餐馆的名称和主打菜系"""
        self.restau_name = restaurant_name;
        self.cuisi_type  = cuisine_type;

    def describe_restaurant(self):
        """打印餐馆名称和菜系"""
        print( self.restau_name + " is the famous restaurant in china.")
        print( self.cuisi_type.title() + " is very delicious.")

    def open_restaurant(self):
        """显示餐馆营业信息"""
        print(self.restau_name.title() + " is opening!")

"""调用餐馆类,显示示例"""
the_most_famous_restaurant = Restaurant("shaxian restaurant","fujian cuisine")

#打印类的两个属性
print("the restaurant name is " + the_most_famous_restaurant.restau_name.title() + ".")
print("the restaurant cuisine  is " + the_most_famous_restaurant.cuisi_type.title() + ".\n")

#调用两个方法/函数
the_most_famous_restaurant.describe_restaurant()
the_most_famous_restaurant.open_restaurant()

最后运行结果为:

[root@centos7 tmp]# python3 restaurant.py 
the restaurant name is Shaxian Restaurant.
the restaurant cuisine  is Fujian Cuisine.

shaxian restaurant is the famous restaurant in china.
Fujian Cuisine is very delicious.
Shaxian Restaurant is opening!

猜你喜欢

转载自blog.csdn.net/zsx0728/article/details/81185064