日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

python入門教程(十一)類方法與靜態(tài)方法

 靜幻堂 2018-10-07
極客饕餮 2018-10-03 08:01:00

Thomas Bergersen - Heart of Courage(純音樂版).mp3

01:58

來自極客饕餮

一 類方法

當(dāng)目前為止,我們所看到的對(duì)象的方法被一個(gè)類的實(shí)例所調(diào)用,然后被傳遞給方法的self參數(shù).

類方法是不同的--它們被一個(gè)類所調(diào)用,它被傳遞給方法的"cls"參數(shù).

類方法用classmethod裝飾器標(biāo)記.

例如:

class Rectangle:
def __init__(self,width,height):
self.width=width
self.height=height
def calculate_area(self):
return self.width*self.height
@classmethod
def new_square(cls,side_length):
return cls(side_length,side_length)
square=Rectangle.new_square(5)
print(square.calculate_area())

結(jié)果:25

new_square是一個(gè)類方法,在類上調(diào)用,而不是在類的實(shí)例上調(diào)用.它返回cls的新對(duì)象.

從技術(shù)上說,參數(shù)self和cls只是慣例;它們可以改變?yōu)槠渌魏螙|西.然而,它們是普遍被遵循的,所以還是固定是用self和cls當(dāng)參數(shù).

二 靜態(tài)方法

靜態(tài)方法與類方法類似,只是它們沒有收到任何額外的參數(shù).

它們用staticmethod裝飾器標(biāo)記.

例如:

class Pizza:
def __init__(self,toppings):
self.toppings=toppings
@staticmethod
def validate_toppings(toppings):
if toppings=="pineapple":
raise ValueError("pineapple")
else:
print ("no pineapple")
ingredients=["cheese","onions","spam",]
if all(Pizza.validate_toppings(i) for i in ingredients):
pizza=Pizza(ingredients)

結(jié)果:

no pineapple

靜態(tài)方法:沒有self或cls參數(shù).

三 屬性

屬性提供了一種自定義實(shí)例屬性訪問的方法.

它們是通過將屬性裝飾器放在一個(gè)方法上面創(chuàng)建的.這意味著當(dāng)訪問與方法同名的實(shí)例屬性時(shí),方法將被調(diào)用.

屬性的一種常見用法就是使屬性為只讀

例如:

class Pizza:
def __init__(self,toppings):
self.toppings=toppings
@property
def pineapple_allowed(self):
return False
pizza=Pizza(["cheese","tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed=True

結(jié)果:

python入門教程(十一)類方法與靜態(tài)方法

這樣pineapple_allowed就成了一個(gè)只讀屬性.

★屬性也可以通過定義setter/getter函數(shù)來設(shè)置.

setter函數(shù)設(shè)置相應(yīng)的屬性值.

getter函數(shù)獲取相應(yīng)的屬性值.

要定義一個(gè)setter,你需要使用一個(gè)與屬性名相同的裝飾器,后面跟著一個(gè)點(diǎn)和setter關(guān)鍵字

這同樣適用于getter函數(shù)

例如:

class Pizza:
def __init__(self,toppings):
self.toppings=toppings
self._pineapple_allowed=False
@property
def pineapple_allowed(self):
return self._pineapple_allowed
@pineapple_allowed.setter
def pineapple_allowed(self,value):
if value:
password=input("請(qǐng)輸入密碼:")
if password=="極客饕餮":
self._pineapple_allowed=value
print(pizza.pineapple_allowed)
else:
raise ValueError("警報(bào),入侵者!")
pizza=Pizza(["cheese","tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed="任何一個(gè)不為假的字符串"

結(jié)果:

python入門教程(十一)類方法與靜態(tài)方法

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多