W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
特性的存在就是將方法偽裝成字段。
property
把類方法當(dāng)做普通字段去調(diào)用,即用對(duì)象調(diào)用的時(shí)候后面不用加括號(hào)
#!/usr/bin/env python
# _*_coding:utf-8 _*_
class Foo:
@property
def Characteristic(self):
print("類方法的特性")
# 創(chuàng)建一個(gè)對(duì)象
obj = Foo()
# 調(diào)用類方法的時(shí)候方法后面不用加括號(hào)
obj.Characteristic
輸出
/usr/bin/python3.5 /home/yangwen/文檔/Python_code/sublime/Week06/Day04/s2.py
類方法的特性
Process finished with exit code 0
setter
設(shè)置類方法的值
#!/usr/bin/env python
# _*_coding:utf-8 _*_
class Foo:
# 獲取Characteristic值
@property
def Characteristic(self):
return "獲取Characteristic值"
# 意思是下面的Characteristic函數(shù)用來給上面的Characteristic函數(shù)設(shè)置值
@Characteristic.setter
def Characteristic(self, value):
return "設(shè)置Characteristic的值"
# 創(chuàng)建一個(gè)對(duì)象
obj = Foo()
# 獲取Characteristic的值
print(obj.Characteristic)
# 設(shè)置Characteristic的值
obj.Characteristic = 123
輸出
/usr/bin/python3.5 /home/yangwen/文檔/Python_code/sublime/Week06/Day04/s2.py
獲取Characteristic值
Process finished with exit code 0
deleter
class Foo:
# 特殊字段
@property
def pp(self):
# 調(diào)用特殊字段的時(shí)候輸出aaa
print("property")
@pp.setter
def pp(self, value):
# 調(diào)用設(shè)置方法的時(shí)候輸出value的值
print(value)
@pp.deleter
def pp(self):
# 調(diào)用刪除方法的時(shí)候輸出del
print("deleter")
# 創(chuàng)建一個(gè)對(duì)象obj
obj = Foo()
# 自動(dòng)執(zhí)行@property
obj.pp
# 自動(dòng)執(zhí)行@pp.setter
obj.pp = 999
# 自動(dòng)執(zhí)行@pp.deleter
del obj.pp
輸出
yangwen@Darker:~$ python3 /home/yangwen/文檔/Python_code/sublime/Week07/s1.py
property
999
delete
class Foo:
def f1(self):
print("f1")
def f2(self, value):
print("f2")
def f3(self):
print("f3")
SpecialFields = property(fget=f1, fset=f2, fdel=f3, doc="我是注釋")
# 創(chuàng)建一個(gè)對(duì)象
obj = Foo()
# 調(diào)用類的f1方法
obj.SpecialFields
# 調(diào)用類的f2方法
obj.SpecialFields = 123
# 調(diào)用類的發(fā)方法
del obj.SpecialFields
# 調(diào)用類的doc,這里只能通過類去訪問,對(duì)象無法訪問
print(Foo.SpecialFields.__doc__)
輸出結(jié)果
yangwen@Darker:~$ python3 /home/yangwen/文檔/Python_code/sublime/Week07/s1.py
f1
f2
f3
我是注釋
本文出自 “一盞燭光” 博客,謝絕轉(zhuǎn)載!
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: