Python基础学习_类的练习

第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

总结:

最后一题,目前水平有限,类方法调用任意关键字实参块还未完全实现,实现后在来补全。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值