对象与反射
常用的对象与反射内置函数:
| 函数 | 说明 | 示例 |
|---|---|---|
type(obj) | 返回对象类型;三参数形式可动态创建类 | type(1) → <class 'int'> |
id(obj) | 返回对象的唯一标识(内存地址),可判断是否同一对象 | id(a) == id(b) |
hash(obj) | 返回哈希值,只有不可变对象可哈希 | hash('a') |
dir(obj) | 列出对象的属性和方法名 | dir(str) |
vars(obj) | 返回对象的 __dict__(属性字典) | vars(p) → {'name': ...} |
hasattr(obj, name) | 是否存在该属性 | hasattr(s, 'upper') |
getattr(obj, name[, default]) | 读取属性,不存在时可返回默认值 | getattr(s, 'upper')() |
setattr(obj, name, value) | 设置属性 | setattr(p, 'age', 18) |
delattr(obj, name) | 删除属性 | delattr(p, 'age') |
示例
class Person:
def __init__(self, name):
self.name = name
p = Person('Alice')
print(type(p)) # <class '__main__.Person'>
print(id(p) == id(p)) # True,同一对象 id 相同
print(hash('abc')) # 哈希值(str 每次运行可能不同)
print([m for m in dir(p) if not m.startswith('__')]) # ['name']
print(vars(p)) # {'name': 'Alice'}
# 动态读写属性
print(hasattr(p, 'name')) # True
print(getattr(p, 'name')) # Alice
print(getattr(p, 'age', '未知')) # 未知,属性不存在返回默认值
setattr(p, 'age', 18) # 等价于 p.age = 18
print(getattr(p, 'age')) # 18
delattr(p, 'age') # 等价于 del p.age
print(hasattr(p, 'age')) # False