python基礎:面向對象的編程 類 示例

示例1:創建和使用類

創建一個名爲Restaurant 的類,其方法__ init __()設置兩個屬性:restaurant_name 和cuisine_type 。創建一個名爲describe_restaurant() 的方法和一個名爲open_restaurant() 的方法,其中前者打印前述兩項信息,而後者打印一條消息,指出餐館正在營業。根據這個類創建一個名爲restaurant 的實例,分別打印其兩個屬性,再調用前述兩個方法。

再向程序中,添加一個名爲number_served 的屬性,並將其默認值設置爲0。根據這個類創建一個名爲restaurant 的實例;打印有多少人在這家餐館就餐過,然後修改這個值並再次打印它。

添加一個名爲set_number_served() 的方法,它讓你能夠設置就餐人數。調用這個方法並向它傳遞一個值,然後再次打印這個值。

添加一個名爲increment_number_served() 的方法,它讓你能夠將就餐人數遞增。調用這個方法並向它傳遞一個這樣的值:你認爲這家餐館每天可能接待的就餐人數。

class Restaurant():
    """創建一個打印餐館的信息"""
    
    def __init__(self,name,type):
        
        self.name = name
        self.type = type
        self.number_served = 0
        
    def describe_restaurant(self):
        
        print('\nRestaurant Name:'+ self.name.title())
        print('\nCuisine Type:'+ self.type.title())
        
        
    def open_restaurant(self):
        
        print('\n'+self.name.title()+' is opening!')
    
    
    def read_number(self):
        
        print("\nNumber of People Eating:"+str(self.number_served))
     
        
    def set_number_served(self,num):
        
        self.number_served = num
        
        
    def increment_served_number(self,increment_number):
        
        self.number_served += increment_number
        
        
mr = Restaurant('和平飯店','四大菜系')
#print(mr.name.title())
mr.describe_restaurant()
mr.open_restaurant()
#mr.number_served=10
mr.set_number_served(500)
mr.increment_served_number(400)
mr.read_number()

#mr1 = Restaurant('water restaurant','chuan cai')
#mr1.describe_restaurant()

'''
Restaurant Name:和平飯店

Cuisine Type:四大菜系

和平飯店 is opening!

Number of People Eating:900
'''

示例2:創建和使用類

創建一個名爲User的類,其中包含屬性first_name 和last_name ,還有用戶簡介通常會存儲的其他幾個屬性。在類User 中定義一個名爲describe_user()的方法,它打印用戶信息摘要;再定義一個名爲greet_user()的方法,它向用戶發出個性化的問候。創建多個表示不同用戶的實例,並對每個實例都調用上述兩個方法。

在爲完成編寫的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。

class User():
    """存儲並打印用戶信息"""
    
    def __init__(self,first_name,last_name,age,location,school,education):
        self.first_name = first_name.title()
        self.last_name = last_name.title()
        self.age = age
        self.location = location.title()
        self.education = education.title()
        self.login_attempts = 0
        
        
    def describe_user(self):
        print('\nFirst Name:'+self.first_name)
        print('Last Name:'+self.last_name)
        print('Age:'+str(self.age))
        print('Location:'+self.location)
        print('Education:'+self.education)
        
        
    def greet_user(self):
        print("Hello,"+self.last_name+' '+self.first_name)
        
        
    def increment_login_attempts(self):
        self.login_attempts += 1
        
        
    def reset_login_attempts(self):
        self.login_attempts = 0
        
    def read_login_attempts(self):
        print("\nLogin Times:"+str(self.login_attempts))
        
        
me = User('erxiao','wang',22,'beijing','BUAA','master')
me.describe_user()
me.greet_user()

for i in range(30):
    me.increment_login_attempts()

me.read_login_attempts()
me.reset_login_attempts()
me.read_login_attempts()

'''
First Name:Erxiao
Last Name:Wang
Age:22
Location:Beijing
Education:Master
Hello,Wang Erxiao

Login Times:30

Login Times:0
'''

示例3:繼承示例1

冰淇淋小店是一種特殊的餐館。編寫一個名爲IceCreamStand 的類,讓它繼承示例1編寫的Restaurant 類。添加一個名爲flavors 的屬性,用於存儲一個由各種口味的冰淇淋組成的列表。編寫一個顯示這些冰淇淋的方法。創建一個IceCreamStand 實例,並調用這個方法。

class Restaurant():
    """創建一個打印餐館的信息"""
    
    def __init__(self,name,type):
        
        self.name = name
        self.type = type
        self.number_served = 0
        
    def describe_restaurant(self):
        
        print('\nRestaurant Name:'+self.name.title())
        print('\nCuisine Type:'+self.type.title())
        
        
    def open_restaurant(self):
        
        print('\n'+self.name.title()+' is opening!')
    
    
    def read_number(self):
        
        print("\nNumber of People Eating:"+str(self.number_served))
     
        
    def set_number_served(self,num):
        
        self.number_served = num
        
        
    def increment_served_number(self,increment_number):
        
        self.number_served += increment_number
        
class IceCreamStand(Restaurant):
    
    def __init__(self,name,type):
        super().__init__(name,type)
        
        self.flavors=['A','B','C']
        
    def display(self):
        for flavor in self.flavors:
            print(flavor)
    

mr = IceCreamStand('北京飯店','魯菜')
#print(mr.name.title())
mr.describe_restaurant()
mr.open_restaurant()
#mr.number_served=10
mr.set_number_served(500)
mr.increment_served_number(400)
mr.read_number()
mr.display()


#mr1 = Restaurant('water restaurant','chuan cai')
#mr1.describe_restaurant()

'''
Restaurant Name:北京飯店

Cuisine Type:魯菜

北京飯店 is opening!

Number of People Eating:900
A
B
C
'''

示例4:繼承示例2

管理員是一種特殊的用戶。編寫一個名爲Admin 的類,讓它繼承示例2編寫的User 類。添加一個名爲privileges 的屬性,用於存儲一個由字符串(如"can add post" 、“can delete post” 、“can ban user” 等)組成的列表。編寫一個名爲show_privileges() 的方法,它顯示管理員的權限。創建一個Admin 實例,並調用這個方法。

class User():
    """存儲並打印用戶信息"""
    def __init__(self,first_name,last_name,age,location,school,education):
        self.first_name = first_name.title()
        self.last_name = last_name.title()
        self.age = age
        self.location = location.title()
        self.education = education.title()
        self.login_attempts = 0
        
        
    def describe_user(self):
        print('\nFirst Name:'+self.first_name)
        print('Last Name:'+self.last_name)
        print('Age:'+str(self.age))
        print('Location:'+self.location)
        print('Education:'+self.education)
        
        
    def greet_user(self):
        print("Hello,"+self.last_name+' '+self.first_name)
        
        
    def increment_login_attempts(self):
        self.login_attempts += 1
        
        
    def reset_login_attempts(self):
        self.login_attempts = 0
        
    def read_login_attempts(self):
        print("\nLogin Times:"+str(self.login_attempts))
        
        
class Admin(User):
    def __init__(self,first_name,last_name,age,location,school,education):
        super().__init__(first_name,last_name,age,location,school,education)
        
        self.privileges = ["can add post","can delete post","can ban user"]
        
        
    def show_privileges(self):
        for value in self.privileges:
            print(value.title())
        
me = Admin('erxiao','wang',22,'beijing','BUAA','master')
me.describe_user()
me.greet_user()

for i in range(30):
    me.increment_login_attempts()

me.read_login_attempts()
me.reset_login_attempts()
me.read_login_attempts()
me.show_privileges()

'''
First Name:Erxiao
Last Name:Wang
Age:22
Location:Beijing
Education:Master
Hello,Wang Erxiao

Login Times:30

Login Times:0
Can Add Post
Can Delete Post
Can Ban User
'''

示例5:繼承,將實例用作屬性

編寫一個名爲Privileges的類,它只有一個屬性——privileges ,其中存儲了示例4所說的字符串列表。將方法show_privileges() 移到這個類中。在Admin 類中,將一個Privileges 實例用作其屬性。創建一個Admin 實例,並使用方法show_privileges() 來顯示其權限。

class User():
    """存儲並打印用戶信息"""
    def __init__(self,first_name,last_name,age,location,school,education):
        self.first_name = first_name.title()
        self.last_name = last_name.title()
        self.age = age
        self.location = location.title()
        self.education = education.title()
        self.login_attempts = 0
        
        
    def describe_user(self):
        print('\nFirst Name:'+self.first_name)
        print('Last Name:'+self.last_name)
        print('Age:'+str(self.age))
        print('Location:'+self.location)
        print('Education:'+self.education)
        
        
    def greet_user(self):
        print("Hello,"+self.last_name+' '+self.first_name)
        
        
    def increment_login_attempts(self):
        self.login_attempts += 1
        
        
    def reset_login_attempts(self):
        self.login_attempts = 0
        
    def read_login_attempts(self):
        print("\nLogin Times:"+str(self.login_attempts))
        
class Privileges():
    def __init__(self):
        self.privileges= ["can add post","can delete post","can ban user"]
    
    def show_privileges(self):
        for value in self.privileges:
            print(value.title())
    
class Admin(User):
    def __init__(self,first_name,last_name,age,location,school,education):
        super().__init__(first_name,last_name,age,location,school,education)
        
        self.privileges = Privileges()
   
me = Admin('erxiao','wang',22,'beijing','BUAA','master')
me.describe_user()
me.greet_user()

for i in range(30):
    me.increment_login_attempts()

me.read_login_attempts()
me.reset_login_attempts()
me.read_login_attempts()
me.privileges.show_privileges()

'''
First Name:Erxiao
Last Name:Wang
Age:22
Location:Beijing
Education:Master
Hello,Wang Erxiao

Login Times:30

Login Times:0
Can Add Post
Can Delete Post
Can Ban User
'''
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章