1. 程式人生 > >類和檔案(第五週)

類和檔案(第五週)

9-1 餐館

class Restaurant():
    def __init__(self, name , type_):
        self.restaurant_name = name
        self.cuisine_type = type_ 
    def describe_restaurant(self):
        print("restaurant_name: " + self.restaurant_name)
        print("cuisine_type: " + self.cuisine_type)
    def open_restaurant(self):
        print("The restaurant is open.")

res = Restaurant("SYSU" , "Chinese food")
res.describe_restaurant()
res.open_restaurant()
程式執行如下:
restaurant_name: SYSU
cuisine_type: Chinese food
The restaurant is open.

9-3 使用者

class User():
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
    def describe_user(self):
        print("First name: "+ self.first_name.title())
        print("Last name: "+ self.last_name.title())
        print("Age: "+ str(self.age))
    def greet_user(self):
        print("Hello " + self.first_name.title() + ' '+self.last_name.title()+"!")

user = User("Ruhua", "Liang", 13)
user.describe_user()
user.greet_user()

程式執行結果如下:

First name: Ruhua
Last name: Liang
Age: 13
Hello Ruhua Liang!

9-7 管理員

class User():
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
    def describe_user(self):
        print("First name: "+ self.first_name.title())
        print("Last name: "+ self.last_name.title())
        print("Age: "+ str(self.age))
    def greet_user(self):
        print("Hello " + self.first_name.title() + ' '+self.last_name.title()+"!")


class Admin(User):
    def __init__(self, first_name, last_name, age, privilege):
        super().__init__(first_name, last_name, age)
        self.privileges = privilege
    def show_privileges(self):
        print(self.privileges.title())

admin = Admin("Ruhua", "Liang", 12 , "can add post")
admin.describe_user()
admin.show_privileges()

執行結果為:

First name: Ruhua
Last name: Liang
Age: 12
Can Add Post

檔案和異常

10-3 訪客

f = open("guest.txt", "w")
name = input("Please input your name\n")
f.write(name)
程式執行後螢幕出現
Please input your name

之後輸入名字 Tom,程式結束,在程式同一目錄出現guest.txt檔案,開啟後顯示“Tom”這個名字。

10-4 訪客名單

f = open("guest_book.txt", "w")
name = "1"
while name != "q":
    name = input("Please input your name.\n")
    if name != "q":
        f.write(name+'\n')
        print("Welcome "+ name)

程式執行後輸入幾個名字後輸入q可以退出程式


guest.txt檔案內容為


10-6 加法運算

while True:
    try:
        a = input("Please input first number\n")
        a = int(a)
        b = input("Please input second number\n")
        b = int(b)
    except ValueError:
        print("Could not input text, please input number")
    else:
        print(str(a) + " + "+ str(b) + " = " + str(a+b))
    if(a == 'q'):break

執行結果如下