一、创建一个简单的类
class Dog():
"""创建一个小狗类"""
def __init__(self,name,age):
"""初始化小狗的属性"""
self.name = name
self.age = age
def decribe(self):
"""描述小狗信息"""
print("The dog's name is "+self.name.title())
print("The dog's age is "+str(self.age))
def sit(self):
"""模拟坐下"""
print(self.name.title() + " can sit !")
def roll(self):
"""模拟打滚"""
print(self.name.title()+ " can roll!")
#实例化对象
info = Dog('mahua',1)
#调用方法
info.decribe()
info.sit()
info.roll()
执行结果:
二、给属性默认值
class Restaurant():
"""创建一个餐馆类"""
def __init__(self,restaurant_name,cuisine_type):
"""初始化餐馆属性"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""描述餐馆属性"""
print("The restaurant's name is "+self.restaurant_name.title())
print("The restanrant's cuisine is "+self.cuisine_type.title())
def open_restaurant(self):
"""打印该餐馆正在营业中"""
print(self.restaurant_name+" is opening...")
def people_number(self):
"""打印有所少人在该餐馆就餐"""
print("There have "+str(self.number_served)+" peole in "+self.restaurant_name)
#创建实例
restaurant_info = Restaurant("sweet love","dessert shop")
#调用方法
restaurant_info.describe_restaurant()
restaurant_info.open_restaurant()
restaurant_info.people_number()
执行结果:
三、修改属性
1、直接修改属性的值。
restaurant_info.number_served = 10
restaurant_info.people_number()
执行结果:
2、通过方法修改属性的值。
def set_number_served(self,doe):
"""在方法中修改餐馆人数的值"""
self.number_served = doe
restaurant_info.set_number_served(20)
restaurant_info.people_number()
执行结果:
3、通过递增的方法修改属性的值。
def increment_number_served(self,incr_doe):
"""递增修改"""
self.number_served += incr_doe
restaurant_info.increment_number_served(20)
restaurant_info.people_number()
执行结果:
四、继承
class Restaurant():
"""创建一个餐馆类"""
def __init__(self,restaurant_name,cuisine_type):
"""初始化餐馆名称和菜品类型"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""描述餐馆的属性"""
print("The restaurant's name is "+self.restaurant_name.title())
print("The cuisine's type is "+self.cuisine_type.title())
def open_restaurant(self):
"""描述餐馆正在营业"""
print("The "+self.restaurant_name.title()+" is opening")
class IceCreamStand(Restaurant):
"""编写冰淇淋小店的子类"""
def __init__(self,restaurant_name,cuisine_type):
"""初始化父类属性,再次初始化餐馆特殊属性"""
super().__init__(restaurant_name,cuisine_type)
self.flavors = ['grape','apple','lemon']
def describe_flavors(self):
""""描述冰淇淋的口味"""
print("The flavors of icecream has: " )
for type in self.flavors:
print(type)
#创建实例
my_restaurant = Restaurant("china restaurant","cuisine of china")
your_restaurant = Restaurant("warm family","sichuan cusion")
mf_restaurant = Restaurant("sweet love","dessert shop")
decr_flavors = IceCreamStand("sweet food ","icecream")
#调用方法
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
your_restaurant.describe_restaurant()
mf_restaurant.describe_restaurant()
decr_flavors.describe_restaurant()
decr_flavors.describe_flavors()
执行结果: