Python 3 内置函数 - delattr()
函数
0. delattr()
函数
- 用于删除属性。
delattr(x, 'y')
相等于del x.y
1. 使用方法
Help on built-in function delattr in module builtins:
## 使用方法
delattr(obj, name, /)
Deletes the named attribute from the given object.
delattr(x, 'y') is equivalent to ``del x.y''
2. 使用示例
>>> class say_anything():
>>> def __init__(self):
>>> self.anything = "hello world."
>>>
>>> def say_print(self):
>>> print(self.anything)
2.1 函数 getattr()
获取属性值 1
>>> a = say_anything() # 创建实例
>>> getattr(a, 'say', -1) # 获取属性值,不存在时返回 -1.
# output:
-1
2.2 函数 setattr()
设置属性值 2
>>> setattr(a, 'say', 'HELLO!') # 设置属性值
>>> a.say # 等同于: getattr(a, 'say')
# output:
'HELLO!'
2.3 函数 delattr()
删除属性值.
>>> delattr(a, 'say') # 删除属性值
>>> getattr(a, 'say', -1) # 获取属性值,不存在时返回 -1.
# output:
-1