第九章 類

9.1 創(chuàng)建和調用類

class Restaurant(): #類名首字母須大寫

? ? def __init__(self, restaurant_name, cuisine_type): #方法:這里前后兩個空格;括號中包含若干形參,其中self必不可少且在最前;self是一個指向實例本身的引用,讓實例能夠訪問類中的屬性和方法.

? ? ? ? self.restaurant_name = restaurant_name

? ? ? ? self.cuisine_type = cuisine_type #屬性:這里獲取存儲在形參中的值;以self為前綴

? ? ? ? self.xxx = 0 #這里是設置默認值

? ? def describe_restaurant(self): #由于不需要額外信息,因此只有一個形參self

? ? ? ? print('The restaurant name is ' + self.restaurant_name.title()

? ? ? ? + ' and its cuisine type is ' + self.cuisine_type.title() + ' .')

? ? def open(self):

? ? ? ? print(self.restaurant_name.title() + ' is open now.')

restaurant = Restaurant('Hollywood', 'italy food') #根據類創(chuàng)建實例

print(restaurant.restaurant_name) #這里訪問屬性(本質是訪問self.restaurant_name)

restaurant.describe_restaurant() #調用方法;這里的實例前綴不要忘記

restaurant.open()

9.2 使用類和實例

9.2.1 修改屬性的值

1.直接修改

restaurant.xxx = 3 #與默認屬性名稱對應即可

2.通過方法修改、遞增

def update_attribute(self, yyy):

? ? self.xxx = yyy

? ? self.xxx += yyy

9.3 繼承

如果要編寫的類是另一個現成類的特殊版本,可使用繼承.
原有類稱為父類,新類稱為子類,
子類還可以定義自己的屬性和方法.

9.3.1 子類的方法super().__init__()

首先是父類的代碼,必須包含在當前文件且在子類前面;

class Yyy(Xxx):

? ? def __init__(self, ..., ..., ...):

? ? ? ? super().__init__(..., ..., ...)

9.3.2 給子類定義屬性和方法

繼承后可添加區(qū)分子類和父類所需的新屬性和方法

就在super().函數下面添加即可,語法為

? ? self.new_attribute = ?#設置新屬性及其初始值

def new_function(self): #添加新方法

9.3.3 ?重寫父類的方法

對于父類的方法,只要不符合子類模擬的實物特性,都可對其進行重寫

9.3.4 將實例用作屬性

將類的一部分作為一個獨立的類提取出來.

先定義新類的名字

class New_class():

? ? def __init__(self, new_attribute):

? ? self.new_attribute = new_attribute 初始化屬性

然后在子類中super()函數后

self.attribute_name = New_class()

9.4 導入類

python允許將類存儲在模塊中,然后在主程序中導入所需的模塊

9.4.1 導入單個類

已有模塊module.py中的類為Class

創(chuàng)建另一文件

from module import Class #注意這里沒有空格,下一行頂格寫

9.4.2 在一個模塊中存儲多個類

同一模塊中的類之間存在某種相關性,可根據需要在一個模塊中存儲任意數量的類.

9.4.3 在一個模塊中導入多個類

將多個類用逗號隔開即可

9.4.4 導入整個模塊

import module

9.4.5 導入所有類

from module import *

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容