Python編程:從入門到實踐——【作業】——第九章(類)


第九章作業

9-1 餐館 : 創建一個名為Restaurant 的類, 其方法__init__( ) 設置兩個屬性: restaurant_name 和cuisine_type 。 創建一個名
為describe_restaurant( ) 的方法和一個名為open_restaurant( ) 的方法, 其中前者打印前述兩項信息, 而后者打印一條消息, 指出餐館正在營業。
根據這個類創建一個名為restaurant 的實例, 分別打印其兩個屬性, 再調用前述兩個方法。
9-2 三家餐館 : 根據你為完成練習 9-1而編寫的類創建三個實例, 並對每個實例調用方法describe_restaurant( ) 。
9-3 用戶 : 創建一個名為User 的類, 其中包含屬性first_name 和last_name , 還有用戶簡介通常會存儲的其他幾個屬性。 在類User 中定義一個名
為describe_user( ) 的方法, 它打印用戶信息摘要; 再定義一個名為greet_user( ) 的方法, 它向用戶發出個性化的問候。
創建多個表示不同用戶的實例, 並對每個實例都調用上述兩個方法。

9-1

class Restaurant():
    '''一個名為Restaurant 的類'''
    def __init__(self,restaurant_name,cuisine_type):
#報錯 object() takes no parameters,修改:,int左右兩個是兩個_不是一個_
'''設置兩個屬性 restaurant_name 和cuisine_type''' self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): #這里忘了給形參self了,報錯describe_restaurant() takes 0 positional arguments but 1 was given print(self.restaurant_name.title()) print(self.cuisine_type.title()) def open_restaurant(self): print('餐館正在營業') restaurant = Restaurant('fu','chinese') restaurant.describe_restaurant() restaurant.open_restaurant() 輸出: Fu Chinese 餐館正在營業

 

 

9-2

class Restaurant():  
    def __init__(self,restaurant_name,cuisine_type):  
        """初始化屬性name和age"""  
        self.restaurant_name = restaurant_name  
        self.cuisine_type = cuisine_type  
    def describe_restaurant(self):  
        print(self.restaurant_name)  
        print(self.cuisine_type)  
    def open_restaurant(self):  
        print('Restaurant is open')  
restaurant1 = Restaurant('A1','B1')    
restaurant1.describe_restaurant()    
restaurant2 = Restaurant('A2','B2')    
restaurant2.describe_restaurant()  
restaurant3 = Restaurant('A3','B3')  
restaurant3.describe_restaurant()  


輸出:
A1
B1
A2
B2
A3
B3

 

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('用戶名稱為:' + self.first_name + self.last_name)

    def greet_user(self):
        print('你好! ' + self.first_name + self.last_name)


user_a = User('Ma', 'Yun')
user_b = User('cheng', 'Long')
user_c = User('Li', 'LianJie')
user_a.describe_user()
user_b.describe_user()
user_c.describe_user()
user_a.greet_user()
user_b.greet_user()
user_c.greet_user()

輸出:
用戶名稱為:MaYun
用戶名稱為:chengLong
用戶名稱為:LiLianJie
你好! MaYun
你好! chengLong
你好! LiLianJie

 

 

 9-4 就餐人數 : 在為完成練習 9-1而編寫的程序中, 添加一個名為number_served 的屬性, 並將其默認值設置為0。 根據這個類創建一個名為restaurant 的實
例; 打印有多少人在這家餐館就餐過, 然后修改這個值並再次打印它。
添加一個名為set_number_served( ) 的方法, 它讓你能夠設置就餐人數。 調用這個方法並向它傳遞一個值, 然后再次打印這個值。
添加一個名為increment_number_served( ) 的方法, 它讓你能夠將就餐人數遞增。 調用這個方法並向它傳遞一個這樣的值: 你認為這家餐館每天可能接待的就
餐人數。
9-5 嘗試登錄次數 : 在為完成練習 9-3而編寫的User 類中, 添加一個名為login_attempts 的屬性。 編寫一個名為increment_login_attempts( ) 的方法,
它將屬性login_attempts 的值加1。 再編寫一個名為reset_login_attempts( ) 的方法, 它將屬性login_attempts 的值重置為0。
根據User 類創建一個實例, 再調用方法increment_login_attempts( ) 多次。 打印屬性login_attempts 的值, 確認它被正確地遞增; 然后, 調用方
法reset_login_attempts( ) , 並再次打印屬性login_attempts 的值, 確認它被重置為0。

9-4

(1)

class Restaurant():
    '''一個名為Restaurant 的類'''
    def __init__(self,restaurant_name,cuisine_type):
        '''設置兩個屬性 restaurant_name 和cuisine_type'''
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        self.number_served = 0
    def set_number_served(self):
        '''設置就餐人數'''
        print('The number of meals ' + str(self.number_served))
    def describe_restaurant(self):
        #這里忘了給形參self了,報錯describe_restaurant() takes 0 positional arguments but 1 was given
        print(self.restaurant_name.title())
        print(self.cuisine_type.title())
    def open_restaurant(self):
        print('餐館正在營業')
restaurant = Restaurant('fu','chinese')
restaurant.describe_restaurant()
restaurant.open_restaurant()
restaurant.set_number_served()

輸出:
Fu
Chinese
餐館正在營業
The number of meals 0

 

(2)

class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.name = restaurant_name
        self.type = cuisine_type
        self.number_served = 0
    def describe_restaurant(self):
        print("Restaurant's name is " + self.name.title() )    
        print("Cuisine type is " + self.type.title())
        print('How many people have dinner in the restaurant?  ' + str(self.number_served))
    def open_restaurant(self):
        print('In operation')
    def set_number_served(self,people):
        self.number_served = people
    def increment_number_served(self,people):
        self.number_served += people

restaurant = Restaurant('金拱門','快餐')
restaurant.describe_restaurant()
restaurant.open_restaurant()
restaurant.set_number_served(10)
restaurant.describe_restaurant()
restaurant.increment_number_served(3)
restaurant.describe_restaurant()

 

9-5

class User():
    def __init__(self,first_name,last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.login_attempts = 0
    def describe_user(self):
        print("First name is " + self.first_name.title() )
        print("Last name is " + self.last_name.title())
    def greet_user(self):
        full_name = self.first_name + ' ' + self.last_name
        print('Hello ' + full_name.title())
    def increment_login_attempts(self):
        self.login_attempts += 1
    def reset_login_attempts(self):
        self.login_attempts = 0
user1 = User('ergou','yang')

user1.describe_user()
user1.increment_login_attempts()
user1.greet_user()
user1.increment_login_attempts()
user1.increment_login_attempts()#調用了3次,增加為3了
print(user1.login_attempts)#必須得打印啊
user1.reset_login_attempts()
print(user1.login_attempts)

如果方法中沒有print則,必須在下面的實例中print才能出來,否則光調用函數沒用的
輸出:
First name is Ergou
Last name is Yang
Hello Ergou Yang
3
0

 

 

 9-6 冰淇淋小店 : 冰淇淋小店是一種特殊的餐館。 編寫一個名為IceCreamStand 的類, 讓它繼承你為完成練習 9-1或練習 9-4而編寫的Restaurant 類。 這兩個版
本的Restaurant 類都可以, 挑選你更喜歡的那個即可。 添加一個名為flavors 的屬性, 用於存儲一個由各種口味的冰淇淋組成的列表。 編寫一個顯示這些冰淇淋
的方法。 創建一個IceCreamStand 實例, 並調用這個方法。
9-7 管理員 : 管理員是一種特殊的用戶。 編寫一個名為Admin 的類, 讓它繼承你為完成練習 9-3或練習 9-5而編寫的User 類。 添加一個名為privileges 的屬性, 用
於存儲一個由字符串(如" can add post" 、 " can delete post" 、 " can ban user" 等) 組成的列表。 編寫一個名為show_privileges( ) 的方法, 它
顯示管理員的權限。 創建一個Admin 實例, 並調用這個方法。
9-8 權限 : 編寫一個名為Privileges 的類, 它只有一個屬性——privileges , 其中存儲了練習9-7 所說的字符串列表。 將方法show_privileges( ) 移到這
個類中。 在Admin 類中, 將一個Privileges 實例用作其屬性。 創建一個Admin 實例, 並使用方法show_privileges( ) 來顯示其權限。
9-9 電瓶升級 : 在本節最后一個electric_car.py版本中, 給Battery 類添加一個名為upgrade_battery( ) 的方法。 這個方法檢查電瓶容量, 如果它不是85, 就將它
設置為85。 創建一輛電瓶容量為默認值的電動汽車, 調用方法get_range( ) , 然后對電瓶進行升級, 並再次調用get_range( ) 。 你會看到這輛汽車的續航里程增
加了。

9-6

class IceCreamStand():
    def __init__(self, name, type):
        self.name = name
        self.type = type
    def flavors(self):
        print('This is a ' + self.name + ' and cuisine is ' + self.type)
IceCreamStand = IceCreamStand('聖代','巧克力')
IceCreamStand.flavors()


輸出:
This is a 聖代 and cuisine is 巧克力

 

 

9-7

class User():
    def __init__(self,first_name,last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.login_attempts = 0
    def describe_user(self):
        print("First name is " + self.first_name.title() )
        print("Last name is " + self.last_name.title())

    def greet_user(self):
        full_name = self.first_name + ' ' + self.last_name
        print('Hello ' + full_name.title())

    def increment_login_attempts(self):
        self.login_attempts += 1

    def reset_login_attempts(self):
        self.login_attempts = 0
class Admin(User):
    '''Admin 的類它繼承你User 類'''
    def __init__(self,first_name,last_name):
        '''初始化父類的屬性'''
        super().__init__(first_name,last_name)#這里沒有self啊!!
        self.privileges = ["can add post", "can delete post", "can ban user"]
    def show_privileges(self):
        print(self.privileges)
user = Admin('ergou','yang')
user.show_privileges()


輸出:['can add post', 'can delete post', 'can ban user']

 

 

9-8

class Privileges():
    def __init__(self):
        self.privileges = ["can add post" ,"can delete post" ,"can ban user"]
    def show_privileges(self):
        print(self.privileges)

class User():
    def __init__(self,first_name,last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.login_attempts = 0
    def describe_user(self):
        print("First name is " + self.first_name.title() )    
        print("Last name is " + self.last_name.title())

    def greet_user(self):
        full_name = self.first_name + ' ' + self.last_name
        print('Hello ' + full_name.title())

    def increment_login_attempts(self):
        self.login_attempts += 1

    def reset_login_attempts(self):
        self.login_attempts = 0

class Admin(User):
    def __init__(self,first_name,last_name):
        super().__init__(first_name,last_name)
        self.privileges = Privileges()


user = Admin('ergou','yang')
user.privileges.show_privileges()

 

 

 9-9

class Car():
    """docstring for Car"""
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
    def get_descriptive_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name
        # 打印里程消息
    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")
        # 更新里程數
    def update_odometer(self, milegeage):
        if milegeage >= self.odometer_reading:
            self.odometer_reading = milegeage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        self.odometer_reading += miles
class Battery():
    """docstring for Battery"""
    def __init__(self, battery_size=70):
        self.battery_size = battery_size
    def describe_battery(self):
        print("This car has a " + str(self.battery_size) + "-kWh battery")
    def upgrade_battery(self):
        if self.battery_size != 85:
            self.battery_size = 85
    def get_range(self):
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
            range = 270
        message = "This car can go approximately " + str(range)
        message += "miles on a full charge."
        print(message)
        self.upgrade_battery()

class ElectricCar(Car):#運用類Car的信息
    """docstring for ElectricCar"""
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery_size = Battery()#運用類Battery的信息
    def describe_battery(self):
        self.battery_size.battery_size()
    def get_range(self):
        self.battery_size.get_range()

my_tesla = ElectricCar('tesla', 'model s', 2016)
my_tesla.get_range()
my_tesla.get_range()


輸出:
This car can go approximately 240miles on a full charge.
This car can go approximately 270miles on a full charge.

 

 

 

 9-10 導入Restaurant 類 : 將最新的Restaurant 類存儲在一個模塊中。 在另一個文件中, 導入Restaurant 類, 創建一個Restaurant 實例, 並調
用Restaurant 的一個方法, 以確認import 語句正確無誤。
9-11 導入Admin 類 : 以為完成練習 9-8而做的工作為基礎, 將User 、 Privileges 和Admin 類存儲在一個模塊中, 再創建一個文件, 在其中創建一個Admin 實例
並對其調用方法show_privileges( ) , 以確認一切都能正確地運行。
9-12 多個模塊 : 將User 類存儲在一個模塊中, 並將Privileges 和Admin 類存儲在另一個模塊中。 再創建一個文件, 在其中創建一個Admin 實例, 並對其調用方
法show_privileges( ) , 以確認一切都依然能夠正確地運行。

9-10

 

#模塊
class Restaurant():
    '''一個名為Restaurant 的類'''
    def __init__(self,restaurant_name,cuisine_type):
       #報錯 object() takes no parameters,修改:,int左右兩個是兩個_不是一個_
        '''設置兩個屬性 restaurant_name 和cuisine_type'''
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
    def describe_restaurant(self):
        #這里忘了給形參self了,報錯describe_restaurant() takes 0 positional arguments but 1 was given
        print(self.restaurant_name.title())
        print(self.cuisine_type.title())
    def open_restaurant(self):
        print('餐館正在營業')

#導入
from Restaurant import Restaurant#英語差限制敲代碼啊
restaurant = Restaurant('fu','chinese')
restaurant.describe_restaurant()
restaurant.open_restaurant()



#輸出
Fu
Chinese
餐館正在營業

 

 

 9-11

#模塊
class Privileges():
    def __init__(self):
        self.privileges = ["can add post" ,"can delete post" ,"can ban user"]
    def show_privileges(self):
        print(self.privileges)

class User():
    def __init__(self,first_name,last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.login_attempts = 0
    def describe_user(self):
        print("First name is " + self.first_name.title() )
        print("Last name is " + self.last_name.title())

    def greet_user(self):
        full_name = self.first_name + ' ' + self.last_name
        print('Hello ' + full_name.title())

    def increment_login_attempts(self):
        self.login_attempts += 1

    def reset_login_attempts(self):
        self.login_attempts = 0

class Admin(User):
    def __init__(self,first_name,last_name):
        super().__init__(first_name,last_name)
        self.privileges = Privileges()


導入:
from moule import Admin
user = Admin('ergou','yang')
user.privileges.show_privileges()

#輸出
['can add post', 'can delete post', 'can ban user']

 

 

9-12

#模塊s1
class Privileges():
    def __init__(self):
        self.privileges = ["can add post" ,"can delete post" ,"can ban user"]
    def show_privileges(self):
        print(self.privileges)
from ss import User#這個是重點
class Admin(User):
    def __init__(self,first_name,last_name):
        super().__init__(first_name,last_name)
        self.privileges = Privileges()

模塊ss#
class User():
    def __init__(self,first_name,last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.login_attempts = 0
    def describe_user(self):
        print("First name is " + self.first_name.title() )
        print("Last name is " + self.last_name.title())

    def greet_user(self):
        full_name = self.first_name + ' ' + self.last_name
        print('Hello ' + full_name.title())

    def increment_login_attempts(self):
        self.login_attempts += 1

    def reset_login_attempts(self):
        self.login_attempts = 0

#導入
from s1 import Admin
user = Admin('ergou','yang')
user.privileges.show_privileges()

#輸出
['can add post', 'can delete post', 'can ban user']

 

 

 

9-13 使用 OrderedDict : 在練習 6-4中, 你使用了一個標准字典來表示詞匯表。 請使用OrderedDict 類來重寫這個程序, 並確認輸出的順序與你在字典中添加鍵
—值對的順序一致。
9-14 骰子 : 模塊random 包含以各種方式生成隨機數的函數, 其中的randint( ) 返回一個位於指定范圍內的整數, 例如, 下面的代碼返回一個1~6內的整數:

from random import randint
x = randint(1, 6)

請創建一個Die 類, 它包含一個名為sides 的屬性, 該屬性的默認值為6。 編寫一個名為roll_die( ) 的方法, 它打印位於1和骰子面數之間的隨機數。 創建一個6面
的骰子, 再擲10次。 創建一個10面的骰子和一個20面的骰子, 並將它們都擲10次。
9-15 Python Module ofthe Week : 要了解Python標准庫, 一個很不錯的資源是網站Python Module ofthe Week。 請訪問http://pymotw.com/ 並查看其中的目 錄, 在其中找一
個你感興趣的模塊進行探索, 或閱讀模塊collections 和random 的文檔。

9-13

from collections import OrderedDict  
favorite_languages = OrderedDict()  
favorite_languages['ken'] = 'C'  
favorite_languages['jack'] = 'PHP'  
favorite_languages['ben'] = 'JAVA'  
favorite_languages['phile'] = 'R'  
  
for k,v in favorite_languages.items():  
    print(k+'___'+v)  

#輸出:
ken___C
jack___PHP
ben___JAVA
phile___R

 

 

9-14

from random import randint
class Die():
    def __init__(self):
        self.sides = 6#這里的給了sides默認值不影響后面的賦值啊
    def roll_die(self):
        x = randint(1, 6)
        self.sides = x
        print(self.sides)
    def roll_die10(self):
        x = randint(1, 10)
        self.sides = x
        print(self.sides)
    def roll_die20(self):
        self.sides = randint(1, 20)
        print(self.sides)

die = Die()
print("----------6  sides-------------")
for i in range(10):
    die.roll_die()
print("----------10 sides-------------")
for i in range(10):
    die.roll_die10()
print("----------20 sides-------------")
for i in range(10):
    die.roll_die20()

 

9-15略

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM