国产探花免费观看_亚洲丰满少妇自慰呻吟_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()函數的功能相同。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南丰县| 邓州市| 积石山| 化隆| 洪雅县| 碌曲县| 平乐县| 崇州市| 秦安县| 武胜县| 深州市| 双鸭山市| 东阳市| 蒙山县| 梁山县| 广水市| 临桂县| 准格尔旗| 西贡区| 定结县| 漳州市| 四会市| 保德县| 孟连| 中牟县| 抚远县| 青冈县| 县级市| 同江市| 曲麻莱县| 隆德县| 金溪县| 府谷县| 遂川县| 兰坪| 绍兴县| 华坪县| 曲靖市| 达孜县| 师宗县| 郯城县|