python 类

放肆的年华 提交于 2020-03-11 11:30:40

在面向对象编程中,你编写表示现实世界中的事物和情景的,根据类来创建对象被称为实例化。在编写类时,你定义一大类对象都有的通用行为,每个对象都自动具备这种通用行为。在定义类时,函数都称为方法

创建类和实例

class Restaurant:  # 在这里,我们定义了一个名为Restaurant的类,根据约定,在Python中,首字母为大写的名称指的就是类
    """一次模式食物店的简单尝试"""  # 我们编写了简单的文档字符串,对这个类的功能进行了简单的描述
    def __init__(self, restaurant_name, cuisine_type):
    """初始化属性的restaurant_name和cuisine_type"""
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        
    def describe_restaurant(self):
    """饭店的简单简介"""
        print("\nThe name of the restaurant is: " + self.restaurant_name)
        print("The food is the restaurant is: " + self.cuisine_type)

    def open_restaurant(self):
    """饭店的经营时间"""
        print(self.restaurant_name.title() + " is opening for 24 hours.")

"""创建了一个实例,通常认为首写字母大写的名称指的是类,而小写的名称指的是根据类创建的实例"""  
restaurant = Restaurant("hai_di_tao", "hotpot")
restaurant.describe_restaurant()
restaurant.open_restaurant()

"""创建了另一个实例"""
restaurant = Restaurant("guangzhou_jiu_jia", "canton_food")
restaurant.describe_restaurant()
restaurant.open_restaurant()

///运行结果为:
The name of the restaurant is: hai_di_tao
The food is the restaurant is: hotpot
Hai_Di_Tao is opening for 24 hours.

The name of the restaurant is: guangzhou_jiu_jia
The food is the restaurant is: canton_food
Guangzhou_Jiu_Jia is opening for 24 hours.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!