delattr() 函数在 Python 中起什么作用?\
pythonserver side programmingprogramming更新于 2025/7/10 7:40:17
Python delattr()
如果对象允许,delattr() 会从对象中删除属性。
语法
delattr() 的语法是 −
delattr(object, name)
delattr() 方法采用两个参数 −
delattr() 不返回任何值(返回 None)。它只删除一个属性(如果对象允许)。
示例
class Coordinate:
x = 12
y = -7
z = 0
point1 = Coordinate()
print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)
delattr(Coordinate, 'z')
print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)
# Raises Error
print('z = ',point1.z)
输出
这给出了输出
Traceback (most recent call last):
('x = ', 12)
('y = ', -7)
File "C:/Users/~.py", line 28, in <module>
('z = ', 0)
print('z = ',point1.z)
--After deleting z attribute--
('x = ', 12)
AttributeError: Coordinate instance has no attribute 'z'
('y = ', -7)
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

