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關鍵字後跟類名和類名後面的:運算符定義的,這允許您在下一個縮進行繼續定義類成員。 以下是班級成員。
- 職業屬性
- 建造師T2】
- 實例屬性
- 屬性
- 課堂方法
也可以在沒有任何成員的情況下定義類。以下示例使用pass關鍵字定義了一個空類。
Example: Define Python Class
class Student:
pass 類實例化使用函數表示法。要創建一個類的對象,只需調用一個類,就像一個無參數的函數,返回該類的一個新對象,如下所示。
Example: Creating an Object of a Class
std = Student() 上圖中,Student()返回Student類的一個對象,該對象被分配給一個本地變量 std。 Student類是一個空類,因為它不包含任何成員。
類別屬性
類屬性是直接在類中定義的變量,由類的所有對象共享。可以使用類名和對象來訪問類屬性。
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.schoolName和std.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 中的構造器用於定義實例的屬性並為其賦值。
實例屬性
實例屬性是附加到類實例的屬性。實例屬性在構造器中定義。
以下示例在構造器中定義實例屬性name和age。
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
微信掃一掃
支付寶掃一掃