《Python编程:从入门到实践》学习打卡10-类和实例的处理

对类和实例的处理

设定默认值

需要进行默认值设定的属性可直接在__init__下进行赋值修改可以不直接写在括号内的参数中

class Car():
    def __init__(self,make,model,year):
        self.make = make
        self.model = model
        self.year = year
        self.miles = 0 # 设定属性默认值
        
    def get_descriptive_name(self):
        long_name = self.make + ' ' + self.model + ' ' + str(self.year)
        return long_name

my_car = Car('honda','accord',2010)
print(my_car.get_descriptive_name())
print(my_car(miles))

修改属性值

直接对属性进行修改

class Dog():
    
    def __init__(self,name,age):
        self.name = name
        self.age = age

my_dog = Dog('wangwang',2)
my_dog.name = 'wangcai'
print(my_dog.name) # 'wangcai'

通过方法进行修改

class Dog():
    
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.height = 0

    def jump(self,height):
        self.height = height #方法对属性值进行修改
        print(self.name.title() + 'could jump ' + str(self.height) + ' meters')
my_dog = Dod('wangwang',2)
my_dog.jump(12)

课后习题

9-4就餐人数

class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        self.number_service = 0

    def describe_restaurant(self):
        print('This restaurant\'s name is ' + self.restaurant_name.title())
        print('It\'s cuisine type is ' + self.cuisine_type)

    def open_restaurant(self):
        print('Opening')
        
    def set_service(self,persons): # 设置当前就餐人数
        self.persons = persons
        print(str(self.persons) + ' persons is eating now')
        
    def increment_number_served(self,step):
        self.persons += step
        print(str(self.persons) + ' may visit the restaurant')

restaurant = Restaurant('tongfu','zhusu')
number = restaurant.number_service
print(str(number) + ' persons have visited this restaurant')
restaurant.number_service = 12 # 修改属性值
print(str(restaurant.number_service) + ' persons have visited this restaurant')

restaurant.set_service(12) # 设置当前就餐人数
restaurant.increment_number_served(25) # 设置就餐递增人数,打印就餐可能人数

9-5尝试登陆次数

class User():
    def __init__(self,first_name,last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.login_attempts = 0
    
    def increment_login_attempts(self):
        self.login_attempts += 1
        print(str(self.login_attempts))

    def  reset_login_attempts(self):
        self.login_attempts = 0
        print(self.login_attempts)

user_1 = User('kobe','brayant')
user_1.increment_login_attempts()
user_1.increment_login_attempts()
user_1.reset_login_attempts()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值