Python 類

Python 是一種完全面向對象的語言。從這些教程開始,您就一直在使用類和對象。Python 程序中的每個元素都是一個類的對象。數字、字符串、列表、詞典等。,在程序中使用的是相應內置類的對象。您可以使用 type() 方法檢索變量或對象的類名,如下所示。

Example: Python Built-in Classes

>>> num=20
>>> type(num)
<class 'int'>            
>>> s="Python"
>>> type(s) 
<class 'str'> 

定義類

Python 中的類可以使用class關鍵字來定義。

class <ClassName>:
    <statement1>
    <statement2>
    .
    .
    <statementN> 

按照上面的語法,一個類是用class關鍵字後跟類名和類名後面的:運算符定義的,這允許您在下一個縮進行繼續定義類成員。 以下是班級成員。

  1. 職業屬性
  2. 建造師T2】
  3. 實例屬性
  4. 屬性
  5. 課堂方法

也可以在沒有任何成員的情況下定義類。以下示例使用pass關鍵字定義了一個空類。

Example: Define Python Class

class Student:
    pass 

類實例化使用函數表示法。要創建一個類的對象,只需調用一個類,就像一個無參數的函數,返回該類的一個新對象,如下所示。

Example: Creating an Object of a Class

std = Student() 

上圖中,Student()返回Student類的一個對象,該對象被分配給一個本地變量 stdStudent類是一個空類,因為它不包含任何成員。

類別屬性

類屬性是直接在類中定義的變量,由類的所有對象共享。可以使用類名和對象來訪問類屬性。

Example: Define Python Class

class Student:
    schoolName = 'XYZ School' 

上圖中schoolName是一個類內部定義的類屬性。除非明確修改,否則所有對象的schoolName值將保持不變。

Example: Define Python Class

>>> Student.schoolName
'XYZ School' 
>>> std = Student()
>>> std.schoolName
'XYZ School' 

可以看到,一個類屬性被Student.schoolNamestd.schoolName訪問。 使用類名更改類屬性的值會在所有實例中改變它。但是,使用實例更改類屬性值不會反映到其他實例或類。

Example: Define Python Class

>>> Student.schoolName = 'ABC School' # change attribute value using class name
>>> std = Student()
>>> std.schoolName
'ABC School'   # value changed for all instances
>>> std.schoolName = 'My School'  # changing instance's attribute
>>> std.schoolName
'My School' 
>>> Student.schoolName # instance level change not reflectd to class attribute
'ABC School' 
>>> std2 = Student()
>>> std2.schoolName
'ABC School' 

下面的例子演示了類屬性count的使用。

Example: Student.py

class Student:
    count = 0
    def __init__(self):
        Student.count += 1 

在上例中,count是 Student 類中的一個屬性。 每當創建新對象時,count的值增加 1。 創建對象後,您現在可以訪問count屬性,如下所示。

Example:

>>> std1=Student()
>>> Student.count
1
>>> std2 = Student()
>>> Student.count
2 

構造器

在 Python 中,每當類的新對象被實例化時,都會自動調用構造器方法,與 C# 或 Java 中的構造器相同。構造器必須有一個特殊的名稱__init__()和一個特殊的參數self

*Note:*The first parameter of each method in a class must be the self , which refers to the calling object. However, you can give any name to the first parameter, not necessarily self. *下面的示例定義了一個構造器。

Example: Constructor

class Student:
    def __init__(self): # constructor method
        print('Constructor invoked') 

現在,無論何時創建Student類的對象,都會調用__init__()構造器方法,如下所示。

Example: Constructor Call on Creating Object

>>>s1 = Student()
Constructor invoked
>>>s2 = Student()
Constructor invoked 

Python 中的構造器用於定義實例的屬性並為其賦值。

實例屬性

實例屬性是附加到類實例的屬性。實例屬性在構造器中定義。

以下示例在構造器中定義實例屬性nameage

Example: Instance Attributes

class Student:
    schoolName = 'XYZ School' # class attribute

    def __init__(self): # constructor
        self.name = '' # instance attribute
        self.age = 0 # instance attribute 

實例屬性可以使用點符號[instance name].[attribute name]來訪問,如下所示。

Example:

>>> std = Student()
>>> std.name
''
>>> std.age
0 

您可以使用點符號設置屬性值,如下所示。

Example:

>>> std = Student()
>>> std.name = "Bill" # assign value to instance attribute
>>> std.age=25        # assign value to instance attribute
>>> std.name          # access instance attribute value
Bill
>>> std.age           # access value to instance attribute
25 

您可以通過構造器指定實例屬性值。除self參數外,以下構造器還包括名稱和年齡參數。

Example: Setting Attribute Values

class Student:
    def __init__(self, name, age): 
        self.name = name
        self.age = age 

現在,您可以在創建實例時指定這些值,如下所示。

Example: Passing Instance Attribute Values in Constructor

>>> std = Student('Bill',25)
>>> std.name
'Bill'
>>> std.age
25 

Note:*You don’t have to specify the value of the self parameter. It will be assigned internally in Python. *您也可以為實例屬性設置默認值。下面的代碼設置構造器參數的默認值。因此,如果在創建對象時沒有提供值,這些值將被分配給後者。

Example: Setting Default Values of Attributes

class Student:
    def __init__(self, name="Guest", age=25)
        self.name=name
        self.age=age 

現在,您可以創建一個具有默認值的對象,如下所示。

Example: Instance Attribute Default Value

>>> std = Student()
>>> std.name
'Guest'
>>> std.age
25 

更多信息請訪問 Python 中的類屬性與實例屬性。

類別屬性

在 Python 中,類中的一個屬性可以使用屬性()函數來定義。

Python 中的property()方法提供了實例屬性的接口。 它封裝實例屬性並提供屬性,與 Java 和 C# 相同。

property()方法以 get、set 和 delete 方法為參數,返回一個property類的對象。

以下示例演示了如何使用property()函數在 Python 中創建屬性。

Example: property()

class Student:
    def __init__(self):
        self.__name=''
    def setname(self, name):
        print('setname() called')
        self.__name=name
    def getname(self):
        print('getname() called')
        return self.__name
    name=property(getname, setname) 

在上例中,property(getname, setname)返回屬性對象,並將其分配給name。 因此,name屬性隱藏了私有實例屬性 __name。 直接訪問name屬性,但是在內部它將調用getname()setname()方法,如下所示。

Example: property()

>>> std = Student()
>>> std.name="Steve"
setname() called
>>> std.name
getname() called
'Steve' 

建議使用物業裝飾代替property()方法。

類方法

您可以使用def關鍵字在一個類中定義任意多的方法。 每個方法必須有第一個參數,一般命名為self,指的是調用實例。

Example: Class Method

class Student:
    def displayInfo(self): # class method
        print('Student Information') 

Self只是類中方法的第一個參數的常規名稱。 對於類的對象x,定義為mymethod(self, a, b)的方法應該稱為x.mymethod(a, b)

上面的類方法可以作為普通函數調用,如下所示。

Example: Class Method

>>> std = Student()
>>> std.displayInfo()
'Student Information' 

方法的第一個參數不需要命名為self。您可以給出任何引用調用方法實例的名稱。 下面的displayInfo()方法將第一個參數命名為obj而不是self,效果非常好。

Example: Class Method

class Student:
    def displayInfo(obj): # class method
        print('Student Information') 

在類中定義沒有self參數的方法會在調用方法時引發異常。

Example: Class Method

class Student:
    def displayInfo(): # method without self parameter
        print('Student Information') 
>>> std = Student()
>>> std.displayInfo() Traceback (most recent call last):
std.displayInfo()
TypeError: displayInfo() takes 0 positional arguments but 1 was given 

該方法可以使用self參數訪問實例屬性。

Example: Class Method

class Student:
    def __init__(self, name, age): 
        self.name = name 
        self.age = age 
    def displayInfo(self): # class method
        print('Student Name: ', self.name,', Age: ', self.age) 

您現在可以調用該方法,如下所示。

Example: Calling a Method

>>> std = Student('Steve', 25)
>>> std.displayInfo()
Student Name: Steve , Age: 25 

刪除屬性、對象、類

您可以使用del關鍵字刪除屬性、對象或類本身,如下所示。

Example: Delete Attribute, Object, Class

>>> std = Student('Steve', 25)
>>> del std.name # deleting attribute
>>> std.name
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
std.name
AttributeError: 'Student' object has no attribute 'name'
>>> del std  # deleting object
>>> std.name  
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
std.name
NameError: name 'std' is not defined
>>> del Student  # deleting class
>>> std = Student('Steve', 25)
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
std = Student()
NameError: name 'Student' is not defined 

原創文章,作者:L9VNA,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/128722.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
L9VNA的頭像L9VNA
上一篇 2024-10-03 23:25
下一篇 2024-10-03 23:25

相關推薦

  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python編程二級證書考試相關現已可以上網購買

    計算機二級Python考試是一項重要的國家級認證考試,也是Python編程的入門考試。與其他考試一樣,Python編程二級證書的考生需要進入正式考試,而為了備考,這篇文章將詳細介紹…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29

發表回復

登錄後才能評論