1、创建Dog类
# 创建Dog类
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title() + " rolled over!")
①在Python中首字母大写的名称指的是类,类中定义的括号为空是因要从空白创建这个类;
②类中的函数称为方法 __init__(self),形参self必不可少。
2、根据类创建实例
# 根据类创建实例
my_dog = Dog('willie',6)
# 访问属性,句点表示法: my_dog.name
print("My dog's name is " + my_dog.name.title())
print("My dog is " + str(my_dog.age) + " years old!")
# 调用方法
my_dog.roll_over()
my_dog.sit()
3、创建多个实例
# 创建多个实例:将每个实例都存储在不同的变量中,或列表、或字典的不同位置
your_dog = Dog('Lucky', 8)
print("My dog's name is " + your_dog.name.title())
print("My dog is " + str(your_dog.age) + " years old!")
your_dog.sit()
练习:
9-1
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.name = restaurant_name
self.type = cuisine_type
def describe_restaurant(self):
print("\nThe restaurant's name is " + self.name.title() + "!")
print("\nThe restaurant is " + self.type + "!")
def open_restsurant(self):
print("\n" + self.name.title() + " is open !")
restaurant_1 = Restaurant('紫光阁', '川菜馆')
restaurant_1.describe_restaurant()
restaurant_1.open_restsurant()
9-2(接9-1的类)
restaurant_1 = Restaurant('紫光阁', '川菜馆')
restaurant_1.describe_restaurant()
restaurant_1.open_restsurant()
restaurant_2 = Restaurant('海底捞', '火锅店')
restaurant_2.describe_restaurant()
restaurant_3 = Restaurant('沙县小吃', '快餐店')
restaurant_3.describe_restaurant()
9-3
# 9-3
class User():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.Last_name = last_name
def describe_user(self):
""""打印客户信息"""
print("\nThe user's name is " + self.first_name.title() + " " + self.Last_name + "!")
def greet_user(self):
"""向用户发出个性化问候"""
name = self.first_name.title() + " " + self.Last_name
print("Hello, " + name)
user1 = User('lily', 'jhon')
user1.describe_user()
user1.greet_user()
# 创建多个实例
user2 = User('Liu', 'Chenxiao')
user2.describe_user()
user2.greet_user()