python是一门面向对象的语言,python中的一切都是对象,例如:类、函数、变量等。那么什么是面向对象呢?面向对象编程是一种程序设计范式,它把程序看作不同的对象互相调用,是一种对具体事物的抽象模型。在面向对象的学习中,听的最多的就是类、类变量、数据成员、实例变量、实例化、方法、对象等基本特征。下面是对我学python面向对象的第一道练习题的说明过程。
首先,创建类。
class Restaurant:
类(class)是用来描述具有相同的属性和方法的对象的集合。它定义了对该集合中每个对象的属性和方法。
其次,创建方法。
def __init__(self,restaurant_name,cuision_type):
self.name = restaurant_name
self.cuision = cuision_type
self.number_severe = 30
def describe_restaurant(self):
print("The restaurant's name is " + self.name )
print("It's type is " + self.cuision)
def open_restaurant(self):
print( '餐馆正在营业')
def eating_number(self,):
print('There are '+ str(self.number_severe) + ' eating')
第一种方法__init__是一种特殊的方法,被称为是类的构造函数或初始化方法,当创建了类的实例后就会调用这个方法。其中self代表类的实例,虽然在调用时不必传入相应的参数,但是在定义方法时这个形参是必须写进去的,而且必须写在其他形参的前面。方法里面以self为前缀的变量都可供类中的所有方法来使用。下面describe_restaurant、open_restaurant、eating_number是用来描述餐馆状况信息的三种方法。
然后,创建实例对象。
restaurant_1 = Restaurant('渔家','Chinese food')
restaurant_2 = Restaurant('KFC','America food')
在一个类中,同时创建了两个实例,即restaurant_1和restaurant_2.
最后,通过调用上述方法来访问属性。
restaurant_1.describe_restaurant()
restaurant_1.open_restaurant()
restaurant_1.eating_number()
restaurant_2.describe_restaurant()