第九章:类
#9-1
class Restaurant():
def __init__(self, name, cuisine_type):
self.name = name
self.type = cuisine_type
def describe_restaurant(self):
print('Restaurant Name: '+self.name)
print('Cuisine Type: '+self.type)
def open_restaurant(self):
print(self.name+' is open now.')
restaurant = Restaurant('McDonald', 'fastfood')
print(restaurant.name)
print(restaurant.type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
#9-6
class Restaurant():
def __init__(self, name, cuisine_type):
self.name = name
self.type = cuisine_type
def describe_restaurant(self):
print('Restaurant Name: '+self.name)
print('Cuisine Type: '+self.type)
def open_restaurant(self):
print(self.name+' is open now.')
class IceCreamStand(Restaurant):
def __init__(self, name, cuisine_type, flavor):
super().__init__(name, cuisine_type)
self.flavor = flavor
def print_flavor(self):
print('Flavors:')
for item in self.flavor:
print(' '+item)
stand = IceCreamStand('Haagen-Dazs', 'Ice cream stand', ['Chocolate', 'Strawberry', 'Mango', 'Macha'])
stand.describe_restaurant()
stand.print_flavor()
#9-10
restaurant.py
class Restaurant():
def __init__(self, name, cuisine_type):
self.name = name
self.type = cuisine_type
def describe_restaurant(self):
print('Restaurant Name: '+self.name)
print('Cuisine Type: '+self.type)
def open_restaurant(self):
print(self.name+' is open now.')
main.py
from restaurant import Restaurant
restaurant = Restaurant('McDonald', 'fastfood')
print(restaurant.name)
print(restaurant.type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
第十章:文件和异常
#10-4
filename = 'guests.txt'
with open(filename, 'w') as file_object:
have_next = True
while (have_next):
name = input('Please input yout name:')
print('Hello, '+name.title())
file_object.write(name+'\n')
temp = input('Are you the last one? (y/n) ')
if (temp == 'y'):
have_next = False
#10-13
import json
def get_stored_username():
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
username = input('Please input your name: ')
stored_username = get_stored_username()
if (username == stored_username):
print('Welcome back '+username+'!')
else:
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print('We\'ll remember you when you come back, '+username+'!')
greet_user()