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() + " roll over!")
my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Willie roll over!
# 9 - 1
class Restaurant():
def __init__(self, name, type):
self.name = name
self.type = type
def describe_restaurant(self):
print("The name of the restaurant is: " + self.name.title() + ".")
print("The type of restaurant is: " + self.type + ".")
def open_restaurant(self):
print("The restaurant is open!")
restaurant = Restaurant('打牙祭', 'fast food')
restaurant.describe_restaurant()
restaurant.open_restaurant()
# 9 - 2
class User():
def __init__(self, first_name, last_name, telephone):
self.first_name = first_name
self.last_name = last_name
self.telephone = telephone
def describe_user(self):
print("First name is: " + self.first_name.title())
print("Last name is: " + self.last_name.title())
print("Telephone is: " + str(self.telephone))
def greet_user(self):
print("Hello, " + self.first_name.title() + self.last_name.title() + "!")
user = User('tao', 'huaxian', 999999999)
user.describe_user()
user.greet_user()
The name of the restaurant is: 打牙祭.
The type of restaurant is: fast food.
The restaurant is open!
First name is: Tao
Last name is: Huaxian
Telephone is: 999999999
Hello, TaoHuaxian!