国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Python > 正文

Python delattr()方法

2023-04-24 19:21:35
字體:
來源:轉載
供稿:網友

Python delattr()是Python的內置函數,其作用是刪除一個對象的指定屬性。

語法格式

delattr(object, name)

參數

object:某類的對象;

name:字符串類型,代表對象的一個屬性名稱。

返回值

該函數沒有返回值

 

使用舉例

下面使用若干例子來說明delattr()函數的具體使用方法。

class Student:
    id = '001'
    name = '丁濤'
    def __init__(self, id,name,age):
        self.id = id
        self.name = name
        self.age = age

stu = Student('002', '丁當', 23)
print(stu.name)
print(Student.name)
delattr(Student, 'name')
print(stu.name)
print(Student.name)

輸出內容如下:

丁當
丁濤
丁當
Traceback (most recent call last):
  File "D:/PY/delattr.py", line 14, in <module>
    print(Student.name)
AttributeError: type object 'Student' has no attribute 'name'
從上面的輸出來看:

刪除類的屬性name后,再次使用時會引發AttributeError錯誤。但未影響使用類定義的對象。

class Student:
    id = '001'
    name = '丁濤'
    def __init__(self, id,name,age):
        self.id = id
        self.name = name
        self.age = age

stu = Student('002', '丁當', 23)
print(Student.name)
print
(stu.name)
delattr(stu, 'name')
print(Student.name)
print(stu.name)

輸出內容如下:

丁濤
丁當
-------
丁濤
丁濤

從上面輸出來看:

當刪除了類對象的屬性后,如果類中有同名的屬性時,則使用類的屬性值。

如果類中未定義對應的屬性,則會引發下面的錯誤:

Traceback (most recent call last):
  File "D:/PY/delattr.py", line 16, in <module>
    print(stu.name)
AttributeError: 'Student' object has no attribute 'name'

如果一個類或類的對象沒有對應的屬性,將引發下面的錯誤:

Traceback (most recent call last):
  File "D:/PY/delattr.py", line 12, in <module>
    delattr(Student, 'name')
AttributeError: name

使用del操作符刪除對象的屬性

使用python的 del 操作符也可以刪除類的一個屬性,其語法格式如下:

del className.attributeName

看下面的例子:

class Student:
    id = '001'
    name = '丁濤'
    def __init__(self, id,name,age):
        self.id = id
        self.name = name
        self.age = age

stu = Student('002', '丁當', 23)
print(Student.name)
print
(stu.name)
del Student.name
print(stu.name)
print(Student.name)

輸出內容如下:

丁濤
丁當
丁當
Traceback (most recent call last):
  File "D:/01Lesson/PY/delattr.py", line 25, in <module>
    print(Student.name)
AttributeError: type object 'Student' has no attribute 'name'

 從輸出來看,其與delattr()函數的功能相同。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜川县| 和龙市| 吕梁市| 石狮市| 抚松县| 涪陵区| 温州市| 仪陇县| 大同县| 平昌县| 鲁甸县| 永年县| 横峰县| 襄樊市| 安化县| 阳东县| 定南县| 辽中县| 汕尾市| 游戏| 卢氏县| 莎车县| 永城市| 安顺市| 大港区| 晋中市| 肥西县| 黑水县| 台州市| 临城县| 军事| 恩平市| 湖州市| 涞水县| 安塞县| 通道| 吉林省| 九龙城区| 宝丰县| 若羌县| 临高县|