Python 中的類是一種封裝數據和行為的機制。通過類,可以將相關的數據和函數封裝在一起,形成一個獨立的邏輯單元。創建一個類就相當于創建了一種新的數據類型,類的實例對象就相當于數據類型的實例化。
在 Python 中,使用 class 關鍵字來定義一個類,類名通常以大寫字母開頭。類中可以定義屬性和方法。屬性用于描述類的特征,方法用于描述類的行為。類中的方法可以訪問和修改類的屬性,從而實現對類的狀態和行為的控制。類中的屬性包括實例屬性和類屬性。實例屬性是指每個對象都會擁有一份的屬性,而類屬性是指與類本身關聯的屬性。實例屬性可以通過 self 關鍵字來創建和訪問,類屬性可以通過在類中直接定義和訪問。
類中的方法分為普通方法、類方法和靜態方法。普通方法是類中最常見的方法,它可以訪問和修改實例屬性,同時也可以調用其他方法和函數。類方法是歸屬于類的一種方法,其第一個參數是類本身,類方法可以訪問和修改類屬性,但不能訪問實例屬性。靜態方法是不歸屬于任何實例或類的方法,它可以被類和實例調用,但不能訪問實例屬性和類屬性。
除了上述概念,類還支持多重繼承(即一個類可以繼承多個父類),以及方法重寫、方法重載等高級特性。
01、類對象的使用
下面以一個實際場景的例子介紹 Python 類的用法。
假設我們要編寫一個程序來管理圖書館的圖書信息。每一本書都有書名、作者、出版社、出版時間等屬性,同時也具有借閱、歸還等方法。這時候,可以定義一個 Book 類來描述每一本書的屬性和行為,具體實現如下:
class Book:
def __init__(self, title, author, publisher, publish_date):
self.title = title
self.author = author
self.publisher = publisher
self.publish_date = publish_date
self.is_borrowed = False
def borrow(self):
if self.is_borrowed:
print(f"{self.title} has been borrowed, please try later.")
else:
self.is_borrowed = True
print(f"{self.title} has been borrowed successfully.")
def return_book(self):
if self.is_borrowed:
self.is_borrowed = False
print(f"{self.title} has been returned successfully.")
else:
print(f"{self.title} has not been borrowed.")
在上述代碼中,我們定義了一個 Book 類,包含了該類的初始化函數__init__(),以及 borrow() 和 return_book() 等方法。其中,init() 方法用于初始化 Book 類的實例對象,在創建實例時傳入所需的參數。borrow() 和 return_book() 方法分別用于借閱和歸還書籍,用于改變 is_borrowed 屬性的值。
接下來,我們可以實例化一個 Book 對象,并調用它的 borrow() 和 return_book() 方法:
book1 = Book("The Alchemist", "Paulo Coelho", "HarperCollins", "1988-01-01")
book1.borrow() # The Alchemist has been borrowed successfully.
book1.return_book() # The Alchemist has been returned successfully.
此外,還可以定義一個 Library 類來封裝管理圖書館的操作。這個類可以包含添加書籍、刪除書籍、查找書籍等方法,使用 Book 對象來存儲每本書的信息。具體實現如下:
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
print(f"{book.title} has been added to the library.")
def remove_book(self, book):
self.books.remove(book)
print(f"{book.title} has been removed from the library.")
def find_book(self, title):
for book in self.books:
if book.title == title:
return book
print(f"{title} is not found in the library.")
return None
在上述代碼中,我們定義了一個 Library 類,包含了該類的初始化函數__init__(),以及 add_book()、remove_book() 和 find_book() 等方法。其中,init() 方法用于初始化 Library 類的實例對象,add_book() 和 remove_book() 方法分別用于添加書籍和刪除書籍,find_book() 方法用于查找書籍。
接下來,我們實例化一個 Library 對象,并向其中添加一些書籍:
python
lib = Library()
book1 = Book("The Alchemist", "Paulo Coelho", "HarperCollins", "1988-01-01")
book2 = Book("The Catcher in the Rye", "J.D. Salinger", "Little, Brown and Company", "1951-07-16")
lib.add_book(book1) # The Alchemist has been added to the library.
lib.add_book(book2) # The Catcher in the Rye has been added to the library.
最后,我們可以通過查找書籍的方式來改變書籍的屬性:?
book = lib.find_book("The Alchemist")
if book:
book.borrow() # The Alchemist has been borrowed successfully.
book = lib.find_book("The Catcher in the Rye")
if book:
book.borrow() # The Catcher in the Rye has been borrowed successfully.
book = lib.find_book("The Alchemist")
if book:
book.return_book() # The Alchemist has been returned successfully.
綜上所述,通過一個圖書館管理系統的例子,我們展示了 Python 類的用法,包括定義類、實例化對象、訪問對象屬性和方法。
02、類對象的繼承
下面以一個人類(Human)的類為例,詳細介紹Python類的用法和對象繼承。
1. 基本概念
在Python中,類是一種自定義的數據類型。類中可以定義變量和方法,用來描述一類對象(各個對象共同的屬性和行為)。
2. 定義類
在Python中,使用class關鍵字定義類,其基本語法格式如下:
class 類名(父類):
屬性1 = 初始值
屬性2 = 初始值
...
方法1()
方法2()
...
其中,父類可以省略不寫,默認繼承于object類。例如,我們定義一個人類:
class Human:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def say_hello(self):
print(f'Hello, my name is {self.name}.')
上述Human類有三個屬性(name、age、gender)和一個方法(say_hello),其中__init__()方法為構造函數,當創建實例對象時會自動調用該方法。
3. 繼承
在Python中,類與類之間可以進行繼承,即一個類可以從另一個類中繼承屬性和方法。語法格式如下:
class 類名(父類):
...
例如,我們定義一個學生類(Student),并繼承于人類(Human):
class Student(Human):
def __init__(self, name, age, gender, grade):
super().__init__(name, age, gender)
self.grade = grade
def study(self):
print(f'{self.name} is studying in grade {self.grade}.')
上述Student類繼承了Human類,即在Student類中可以訪問Human類中定義的屬性和方法。
4. 創建子類對象
創建子類對象時,會自動調用父類的構造函數,例如:
lisi = Student('李四', 16, '男', 10)
此時,lisi既擁有Student類中定義的屬性和方法,也擁有Human類中定義的屬性和方法,因為Student類繼承了Human類。
print(lisi.gender) # 訪問Human類中的屬性
lisi.say_hello() # 調用Human類中的方法
lisi.study() # 調用Student類中的方法
輸出結果為:
男
Hello, my name is 李四.
李四 is studying in grade 10.
綜上所述,Python中的類是一種自定義的數據類型,可用于描述一類對象。通過類可以創建對象,訪問對象的屬性和方法,還可以進行繼承。
掃碼二維碼 獲取免費視頻學習資料
- 本文固定鏈接: http://www.stbrigidsathleticclub.com/post/11293/
- 轉載請注明:轉載必須在正文中標注并保留原文鏈接
- 掃碼: 掃上方二維碼獲取免費視頻資料
查 看2022高級編程視頻教程免費獲取