第9章练习题
1 餐馆
class Restaurant():
"""显示餐馆信息"""
## 餐馆属性
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
## 餐馆方法
def describle_restaurant(self):
print("The restaurant name is " + self.restaurant_name.title() + ".")
print("The restaurant cuisine_type is " + self.cuisine_type.title() + '.')
def open_restaurant(self):
print(self.restaurant_name + " 餐馆正在营业,欢迎你的到来!")
实例化对象 通过类创建对象叫做实例化
restaurant = Restaurant("beijingdake", 'huoze')
打印对象信息
调用Restaurant方法
print("name",": ",restaurant.restaurant_name)
print("rtype",": ",restaurant.cuisine_type)
restaurant.describle_restaurant()
restaurant.open_restaurant()
结果:
name : beijingdake
rtype : huoze
The restaurant name is Beijingdake.
The restaurant cuisine_type is Huoze.
beijingdake 餐馆正在营业,欢迎你的到来!
2 三家餐馆
实例化对象 实例化:有类创建对象叫做实例化
r1 = Restaurant('laoguo', 'li')
r2 = Restaurant('kuli', 'opur')
r3 = Restaurant('klju', 'opqjfe')
调用对象方法
r1.describle_restaurant()
r2.describle_restaurant()
r3.describle_restaurant()
结果:
The restaurant name is Laoguo.
The restaurant cuisine_type is Li.
The restaurant name is Kuli.
The restaurant cuisine_type is Opur.
The restaurant name is Klju.
The restaurant cuisine_type is Opqjfe.
3 Uer类
定义User类
class User():
"""显示用户信息"""
## 用户属性
def __init__(self,first_name,last_name,**user_info):
self.first_name = first_name
self.last_name = last_name
for k,v in user_info.items():
setattr(self, k, v)
## 用户方法
def describle_user(self):
print("name" ," : ",self.first_name)
print("last_name"," : ",self.last_name)
创建对象,实例化:从类来创建对象
u1 = User('wang', 'wei', location = 'shanghai',work = 'teacher')
u1.describle_user()
print(u1.location)
print(u1.work)
结果:
name : wang
last_name : wei
shanghai
teacher
总结:
最后一题,目前水平有限,类方法调用任意关键字实参块还未完全实现,实现后在来补全。