Python 是一種「面向對象的編程語言」。這種說法意味着大部分代碼都是在一種稱為類的特殊構造的幫助下實現的。程序員利用類來保持相關的東西在一起。我們可以藉助關鍵字「類」來實現這一點,這是一組面向對象的結構。
在以下教程中,我們將涵蓋以下主題:
- 什麼是階級?
- 如何創建一個類?
- 什麼是方法?
- 如何進行對象實例化?
- 如何在 Python 中創建實例屬性?
那麼,讓我們開始吧。
類被認為是用於創建對象的代碼模板。對象由成員變量組成,並具有與之相關的行為。在像 Python 這樣的編程語言中,我們可以使用關鍵字「class」創建一個類。
我們可以在類構造器的幫助下創建一個對象。該對象將被識別為類的實例。在 Python 中,我們可以使用以下語法創建實例:
語法:
Instance = class(arguments)
我們可以使用前面閱讀的 class 關鍵字創建一個類。現在讓我們考慮一個例子,演示如何創建一個沒有功能的簡單的空類。
示例:
# defining a class
class College:
pass
# instantiating the class
student = College()
# printing the object of the class
print(student)
輸出:
<__main__.college object="" at="">
說明:
在上面的代碼片段中,我們已經將一個空類定義為「學院」。然後,我們使用學生作為對象實例化該類,並為用戶打印該對象。
一個類本身沒有任何用處,除非有一些功能與之相關聯。我們可以通過設置屬性來定義這些功能,屬性充當與這些屬性相關聯的數據和功能的容器。我們稱這些函數為方法。
我們可以用學院這個名字來定義下面的班級。這個班級會有一個屬性學生 _ 姓名。
示例:
# defining a class
class College:
student_name = "Alex" # setting an attribute 'student_name' of the class
...
說明:
在上面的代碼片段中,我們已經將一個類定義為「學院」。然後我們在類中定義了一個屬性「學生名」。
現在,讓我們嘗試將類分配給一個變量。這就是所謂的對象實例化。然後,我們將能夠在點的幫助下訪問類中可用的屬性。操作員。讓我們考慮下面的例子來說明這一點:
示例:
# defining a class
class College:
student_name = "Alex" # setting an attribute 'student_name' of the class
# instantiating the class
student = College()
# printing the object of the class
print(student.student_name)
輸出:
Alex
說明:
在上面的代碼片段中,我們遵循了前面示例中的相同過程。但是,我們現在已經實例化了類,並使用對象打印了屬性值。
一旦我們定義了屬於類的屬性,我們現在可以定義幾個函數來訪問類屬性。這些函數被稱為方法。每當我們定義一個方法時,總是需要給方法的第一個參數提供一個名為「self」的關鍵字。
讓我們考慮下面的例子來證明這一點。
示例:
# defining a class
class College:
student_name = "Alex" # setting an attribute 'student_name' of the class
def change_std_name(self, new_std_name):
self.student_name = new_std_name
# instantiating the class
student = College()
# printing the object of the class
print("Name of the student:", student.student_name)
# changing the name of the student using the change_std_name() method
student.change_std_name("David")
# printing the object of the class
print("New name of the student:", student.student_name)
輸出:
Name of the student: Alex
New name of the student: David
說明:
在上面的代碼片段中,我們定義了一個類並定義了它的屬性。然後我們定義了一個方法 change_std_name 來將屬性的前一個值更改為另一個值。然後,我們實例化了這個類,並為用戶打印了所需的輸出。因此,我們可以觀察另一個屬性的值。
原創文章,作者:FZYBL,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/127098.html