对类和实例的处理
设定默认值
需要进行默认值设定的属性可直接在__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()