Python中创建类
在python中创建一个类并不像C++中使用new关键字,而是使用class,因而python中也没有new这个关键字。
定义类具体格式如下例所示:
'''
类的创建及实例化
'''
class Restaurant():
def __init__(self,name,rtype,owner=""):
self.name=name
self.rtype=rtype
self.owner=owner
def describe_restaurant(self):
print("The restaurant's name is:"+self.name.title())
print("The type of the restaurant is:"+self.rtype.title())
def open_restaurant(self):
print(self.name.title()+"is running now.")
尤其要注意其中的__init__方法使用来初始化一个对象的默认方法,在"init"的前后都是两个下划线,由于在不同的编辑器下可能显示不同看起来有时候会像是一条下划线,因此有时候会对初学者造成误导。如果使用了只有一条下划线的init方法,会产生以下错误信息:
TypeError Traceback (most recent call last)
<ipython-input-21-420424297245> in <module>()
14 print(self.name.title()+"is running now.")
15
---> 16 my_restaurant = Restaurant("HKU","school","Hantongyou")
17 my_restaurant.describe_restaurant()
18 my_restaurant.open_restaurant()
TypeError: Restaurant() takes no arguments