欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中delattr刪除對象方法的代碼分析

 更新時間:2020年12月15日 15:26:14   作者:小妮淺淺  
在本篇文章里小編給大家分享了一篇關(guān)于python中delattr刪除對象方法的代碼分析內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。

最近我們針對對象屬性這塊,介紹了不少關(guān)于測試屬性的方法。在進行一系列測試后,我們發(fā)現(xiàn)這個屬性并不需要,這時候就要用到刪除的功能。在python中可以選擇delattr函數(shù)刪除對象的屬性,基于它的刪除功能,是否能擴展到刪除的對象的方法上,在我們對delattr函數(shù)進行全面了解后,展開實例的測試。

1.說明  

函數(shù)作用用來刪除指定對象的指定名稱的屬性,和setattr函數(shù)作用相反。

不能刪除對象的方法。

2.參數(shù)

object -- 對象。

name -- 必須是對象的屬性。

3.返回值

無。

4.實例

>>> 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
>>>

通過測試的結(jié)果,我們可以看出delattr函數(shù)并不能刪除對象的方法,只針對于屬性有刪除的功能,不然就會報錯。相信本篇的實戰(zhàn)代碼演示能讓大家對注意點有一個深刻的印象。

Python3基礎(chǔ) delattr 刪除對象的屬性

class MyClass:
  # num是類屬性
  num = 1

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


def main():
  test = MyClass("shemingli")

  # 刪除類屬性
  # 刪除類屬性要寫類名,而不是實例名
  delattr(MyClass, "num")

  # 刪除實例屬性
  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()

到此這篇關(guān)于python中delattr刪除對象方法的代碼分析的文章就介紹到這了,更多相關(guān)python中delattr可以刪除對象方法嗎內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論