如何在python中利用delattr刪除對(duì)象?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

1.說(shuō)明
函數(shù)作用用來(lái)刪除指定對(duì)象的指定名稱的屬性,和setattr函數(shù)作用相反。
不能刪除對(duì)象的方法。
2.參數(shù)
object -- 對(duì)象。
name -- 必須是對(duì)象的屬性。
3.返回值
無(wú)。
4.實(shí)例
>>> a.sayHello <bound method A.sayHello of <__main__.A object at 0x03F014B0>> >>> delattr(a,'sayHello') #不能用于刪除方法 Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> delattr(a,'sayHello') AttributeError: sayHello >>>
通過(guò)測(cè)試的結(jié)果,我們可以看出delattr函數(shù)并不能刪除對(duì)象的方法,只針對(duì)于屬性有刪除的功能,不然就會(huì)報(bào)錯(cuò)。相信本篇的實(shí)戰(zhàn)代碼演示能讓大家對(duì)注意點(diǎn)有一個(gè)深刻的印象。
class MyClass:
# num是類屬性
num = 1
def __init__(self, name):
self.name = name
def main():
test = MyClass("shemingli")
# 刪除類屬性
# 刪除類屬性要寫(xiě)類名,而不是實(shí)例名
delattr(MyClass, "num")
# 刪除實(shí)例屬性
delattr(test, "name")
"""
def delattr(o: Any, name: str)
Inferred type: (o: Any, name: str) -> None
Deletes the named attribute from the given object.
delattr(x, 'y') is equivalent to ``del x.y''
"""
# 注:如果屬性不存在,就拋出異常
if __name__ == '__main__':
main()看完上述內(nèi)容,你們掌握如何在python中利用delattr刪除對(duì)象的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
文章名稱:如何在python中利用delattr刪除對(duì)象-創(chuàng)新互聯(lián)
本文來(lái)源:http://www.chinadenli.net/article26/diopjg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開(kāi)發(fā)、靜態(tài)網(wǎng)站、用戶體驗(yàn)、外貿(mào)建站、服務(wù)器托管、域名注冊(cè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容