溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python類的基本使用方法有哪些

發(fā)布時(shí)間:2022-10-21 14:31:07 來(lái)源:億速云 閱讀:130 作者:iii 欄目:編程語(yǔ)言

本篇內(nèi)容主要講解“Python類的基本使用方法有哪些”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“Python類的基本使用方法有哪些”吧!

1、面向?qū)ο?/strong>

類(class):是一種用來(lái)描述具有相同屬性和方法的對(duì)象的集合。

類變量:類變量在整個(gè)實(shí)例化的對(duì)象中是公用的。一般定義在類中且在函數(shù)體之外。

方法:類中的函數(shù)

數(shù)據(jù)成員:類變量或者實(shí)例變量用于處理類及其實(shí)例對(duì)象的相關(guān)的數(shù)據(jù)。

方法重寫(xiě):如果從父類繼承的方法不能滿足子類的需求,可以對(duì)其進(jìn)行改寫(xiě),這個(gè)過(guò)程叫方法的覆蓋(override),也稱為方法的重寫(xiě)。

局部變量:定義在方法中的變量,只作用于當(dāng)前實(shí)例的類。

實(shí)例變量:在類的聲明中,屬性是用變量來(lái)表示的,這種變量就稱為實(shí)例變量,實(shí)例變量就是一個(gè)用 self 修飾的變量。

繼承:即一個(gè)派生類(derived class)繼承基類(base class)的字段和方法。繼承也允許把一個(gè)派生類的對(duì)象作為一個(gè)基類對(duì)象對(duì)待。就像我們定義一個(gè)fruit(水果)類,然后又定義了一個(gè)fruit類的派生類apple(蘋(píng)果),它有著fruit類的一些屬性和方法,也有著自己的一些獨(dú)特的屬性和方法,和fruit類是一種’is-a’的關(guān)系。

實(shí)例化:類的一個(gè)具體對(duì)象,類像當(dāng)于一個(gè)模板,只有我們將其實(shí)例化為一個(gè)對(duì)象后才能對(duì)其進(jìn)行相應(yīng)的操作。

對(duì)象:通過(guò)類定義的數(shù)據(jù)結(jié)構(gòu)實(shí)例。對(duì)象包括兩個(gè)數(shù)據(jù)成員(類變量和實(shí)例變量)和方法。


2、類定義

定義一個(gè)類:

class ClassName:....    ....    ....

類名建議采用駝峰式命名,或者全部大寫(xiě)字母


3、使用類對(duì)象方法

類對(duì)象支持兩種操作:屬性引用和實(shí)例化

屬性引用:和python中的其他語(yǔ)法一樣,obj.name

在類中帶__的屬性為類的私有屬性,私有屬性在類外部無(wú)法直接訪問(wèn),像__name.

class Fruit:#這是類的一個(gè)基本屬性self.number = 100def get_number(self):                a = self.number + 100return a

f = Fruit()print('We have {0} fruits'.format(f.number))print('We have {0} fruits'.format(f.get_number()))

輸出結(jié)果:

We have 100 fruitsWe have 200 fruits

4、構(gòu)造方法

python類中有一個(gè)名為_(kāi)_init__()的特殊方法,叫構(gòu)造方法,該方法在類進(jìn)行實(shí)例化時(shí)會(huì)自動(dòng)進(jìn)行調(diào)用(可以用于類屬性初始化等),類似C++里面類的構(gòu)造函數(shù)。

def __init__(self):self.data = []

類定義了 __init__() 方法,類的實(shí)例化操作會(huì)自動(dòng)調(diào)用__init__()方法。

class Fruit:def __init__(self):                print('你已經(jīng)實(shí)例化了一個(gè)對(duì)象')
f = Fruit()

輸出結(jié)果

你已經(jīng)實(shí)例化了一個(gè)對(duì)象

init_() 方法可以有參數(shù),參數(shù)通過(guò) init() 傳遞到類的實(shí)例化操作上。

class Complex:def __init__(self,real,image):self.r = realself.i = imagedef get_complex(self):                print('complex real is %.2f , image is %.2f'%(self.r,self.i))
a = Complex(3.5,-3)a.get_complex()

輸出結(jié)果如下:

complex real is 3.50 , image is -3.00

self代表類的實(shí)例,而非類。類的方法與普通的函數(shù)只有一個(gè)特別的區(qū)別——它們必須有一個(gè)額外的第一個(gè)參數(shù)名稱, 按照慣例它的名稱是 self。但self并不是Python中的關(guān)鍵字哦。

不知是否可以這樣理解,self就代表的是你按照一個(gè)類實(shí)例化一個(gè)對(duì)象后的對(duì)象的地址。很像C++類中this指針

class Test:def prt(self):        print(self)        print(self.__class__)
t = Test()t.prt()

輸出:

<__main__.Test object at 0x0000025EC6D45608><class '__main__.Test'>

5、類的方法

在類的內(nèi)部,使用 def 關(guān)鍵字來(lái)定義一個(gè)方法,與一般函數(shù)定義不同,類方法必須包含參數(shù) self, 且為第一個(gè)參數(shù)。如果不需要self傳遞參數(shù),需要在函數(shù)前面加上@staticmethod,表示靜態(tài)方法

class Complex:def __init__(self, real=None, image=None):self.r = realself.i = image
def get_complex(self):        print('complex real is %.2f , image is %.2f' % (self.r, self.i))
    @staticmethoddef test(a, b):        print('complex real is %.2f , image is %.2f' % (a, b))

a = Complex(3.5, -3)a.get_complex()
b = Complex()b.test(3, -2)

輸出結(jié)果

complex real is 3.50 , image is -3.00complex real is 3.00 , image is -3.00

6、繼承

Python 同樣支持類的繼承,格式如下:

class Derivedclassname(Baseclassname):    ...    ...

Baseclassname(基類名)必須與派生類定義在一個(gè)作用域內(nèi)。除了類,還可以用表達(dá)式,基類定義在另一個(gè)模塊中時(shí)這一點(diǎn)非常有用:

class Fruit:    def __init__(self,sweet):        self.sweetness = sweet    def describe(self):        print('Our fruit has a sweetness of %.2f'%self.sweetness)
class Apple(Fruit):#單繼承,繼承fruit類    def __init__(self,sweet,color):        self.color = color        Fruit.__init__(self,sweet)    def describe(self):#改寫(xiě)基類fruit的方法        print('Our apple has a sweetness of {0:.2f}%,and color is {1}'.format(self.sweetness,self.color))

apple = Apple(62.2,'red')apple.describe()

輸出:

Our apple has a sweetness of 62.20%,and color is red

多繼承

Python同樣可以繼承多個(gè)基類:

class Derivedclassname(basename1,basename2,...):    ...    ...    ...

需要注意圓括號(hào)中父類的順序,若是父類中有相同的方法名,而在子類使用時(shí)未指定,python從左至右搜索,即方法在子類中未找到時(shí),從左到右查找父類中是否包含方法。

class Fruit:def __init__(self, sweet):        self.sweetness = sweetdef describe(self):        print('Our fruit has a sweetness of %.2f' % self.sweetness)

class Food:def __init__(self, uprice, num):        self.unit_price = uprice        self.number = num        self.total_price = num * upricedef cost(self):        print('You need to pay {0:.3} yuan, thank you'.format(self.total_price))

class Apple(Fruit, Food):def __init__(self, sweet, color, uprice, num):        self.color = color        Fruit.__init__(self, sweet)        Food.__init__(self, uprice, num)def describe(self):        print('Our fruit has a sweetness of {0:.2f}%,and color is {1}'.format(self.sweetness, self.color))
apple = Apple(62.2,'red',3.5,21)apple.describe()apple.cost()

輸出:

Our fruit has a sweetness of 62.20%,and color is redYou need to pay 73.5 yuan, thank you

7、方法重寫(xiě)

如果父類方法的功能不能滿足你的需求,你可以在子類重寫(xiě)你父類的方法,如果想調(diào)用已經(jīng)被覆蓋的基類方法,可以用super(子類名,子類實(shí)例對(duì)象名).父類方法

class Parent_class:def Method(self):         print ('父類方法')

class Child_class(Parent_class): # 定義子類def Method(self):        print ('子類方法')

c = Child_class()                # 子類實(shí)例化c.Method()                  # 子類調(diào)用重寫(xiě)方法super(Child_class,c).Method()    #用子類對(duì)象調(diào)用父類已被覆蓋的方法

子類繼承父類構(gòu)造函數(shù)

如果在子類中需要父類的構(gòu)造方法就需要顯式地調(diào)用父類的構(gòu)造方法,或者不重寫(xiě)父類的構(gòu)造方法。

class A:def __init__(self, x, y):        self.x = x        self.y = y        print('pos is ({0},{1})'.format(self.x, self.y))
def xxx(self):        print('parent now')

class B(A):def xxx(self):        print('child now')

b = B(10, 3)b.xxx()

輸出

pos is (10,3)child now

如果重寫(xiě)了__init__ 時(shí),實(shí)例化子類,就不會(huì)調(diào)用父類已經(jīng)定義的 __init__。

如果重寫(xiě)了__init__ 時(shí),要繼承父類的構(gòu)造方法,可以使用 super 關(guān)鍵字super(子類,self).__init__(參數(shù)1,參數(shù)2,....),或者父類名稱.__init__(self,參數(shù)1,參數(shù)2,...)


8、類的私有屬性

兩個(gè)下劃線開(kāi)頭,聲明該屬性為私有,像__name不能在類的外部被使用或直接訪問(wèn)。在類內(nèi)部的方法中使用時(shí) self.__name。

class JustCounter:     __secretCount = 0  # 私有變量    publicCount = 0  # 公開(kāi)變量
def count(self):        self.__secretCount += 1        self.publicCount += 1       print(self.__secretCount)

counter = JustCounter()counter.count()counter.count()print(counter.publicCount)print(counter.__secretCount)  # 報(bào)錯(cuò),實(shí)例不能訪問(wèn)私有變量
Traceback (most recent call last):File "test.py", line 16, in <module>    print (counter.__secretCount)  # 報(bào)錯(cuò),實(shí)例不能訪問(wèn)私有變量AttributeError: 'JustCounter' object has no attribute '__secretCount'

兩個(gè)下劃線開(kāi)頭,聲明該方法為私有方法,像__private_method,只能在類的內(nèi)部調(diào)用 ,不能在類的外部調(diào)用。self.___private_method。

class Site:def __init__(self, name, url):        self.name = name  # public        self.__url = url  # private
def who(self):        print('name  : ', self.name)        print('url : ', self.__url)
def __foo(self):  # 私有方法        print('這是私有方法')
def foo(self):  # 公共方法        print('這是公共方法')        self.__foo()

x = Site('***', 'www.xxx.com')x.who() # 正常輸出x.foo() # 正常輸出x.__foo()  # 報(bào)錯(cuò)

輸出:

'''name  :  ***url :  www.***.com這是公共方法這是私有方法Traceback (most recent call last):  File "F:\Python\Program\test.py", line 61, in <module>    x.__foo()      # 報(bào)錯(cuò)AttributeError: 'Site' object has no attribute '__foo''''

類的專有方法

__init__ : 構(gòu)造函數(shù),在生成對(duì)象時(shí)調(diào)用,類似C++構(gòu)造函數(shù)

__del__: 析構(gòu)函數(shù),釋放對(duì)象時(shí)使用,類似C++析構(gòu)函數(shù),常用在釋放申請(qǐng)的內(nèi)存空間

__repr__: 打印,轉(zhuǎn)換。這個(gè)個(gè)函數(shù)就是在打印類的時(shí)候,控制類輸出的字符串

class Name:def __init__(self, name):        self.name = name

print(Name('s'))
'''<__main__.Name object at 0x0000023744AFD248>'''
class Name:def __init__(self,name):        self.name = name
def __repr__(self): #控制了在打印類時(shí)候的輸出          return 'Name({!r})'.format(self.name)

print(Name('s'))
'''Name('s')'''

__setitem__ : 每當(dāng)屬性被賦值的時(shí)候都會(huì)調(diào)用該方法,因此不能再該方法內(nèi)賦值 self.name = value 會(huì)死循環(huán)

__getitem__: 當(dāng)訪問(wèn)不存在的屬性時(shí)會(huì)調(diào)用該方法

__len__: 獲得長(zhǎng)度,如果一個(gè)類表現(xiàn)得像一個(gè)list,要獲取有多少個(gè)元素,就得用len() 函數(shù)。要讓len()函數(shù)工作正常,類必須提供一個(gè)特殊方法__len__(),它返回元素的個(gè)數(shù)。

class CountList:def __init__(self, *args):        self.list = [x for x in args]        self.count = self.__len__()
def __len__(self):         return len(self.list)
def get_count(self):         return self.count

a = CountList(1, 2, 3, 4, 4, 5)print(a.get_count())print(len(a))

__cmp__: 比較運(yùn)算

__call__: 函數(shù)調(diào)用

__add__: 加運(yùn)算

__sub__: 減運(yùn)算

class MyClass:
def __init__(self, height, weight):        self.height = height        self.weight = weight
# 兩個(gè)對(duì)象的長(zhǎng)相加,寬不變.返回一個(gè)新的類def __add__(self, others):        return MyClass(self.height + others.height, self.weight + others.weight)
# 兩個(gè)對(duì)象的寬相減,長(zhǎng)不變.返回一個(gè)新的類def __sub__(self, others):        return MyClass(self.height - others.height, self.weight - others.weight)
# 說(shuō)一下自己的參數(shù)def intro(self):        print("高為", self.height, " 重為", self.weight)

def main():    a = MyClass(height=10, weight=5)    a.intro()
    b = MyClass(height=20, weight=10)    b.intro()
    c = b - a    c.intro()
    d = a + b    d.intro()

if __name__ == '__main__':    main()
'''高為 10  重為 5高為 20  重為 10高為 10  重為 5高為 30  重為 15'''

__mul__: 乘運(yùn)算

__truediv__: 除運(yùn)算

__mod__: 求余運(yùn)算

__pow__: 乘方

同樣的。類的專有方法也可以重寫(xiě)

到此,相信大家對(duì)“Python類的基本使用方法有哪些”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI