文章目录
1. .get() 方法
1.1 作用
字典的.get()方法用于安全地获取字典中的值,如果键不存在不会报错,而是返回默认值。
1.2 使用场景
# 普通字典访问(键不存在会报错)
person = {'name': 'Alice', 'age': 25}
print(person['name']) # Alice
# print(person['address']) # KeyError!
# 使用 .get() 安全访问
print(person.get('name')) # Alice
print(person.get('address')) # None (不报错)
print(person.get('address', '未知')) # 未知 (设置默认值)
1.3 什么时候用?
- 当不确定键是否存在时
- 希望键不存在时返回特定默认值而不是报错
- 避免使用try-except处理KeyError
2. hasattr() 函数
2.1 作用
检查对象是否具有指定的属性或方法。
2.2 使用场景
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
return f"Hello, {self.name}"
person = Person("Bob")
# 检查属性
print(hasattr(person, 'name')) # True
print(hasattr(person, 'age')) # False
# 检查方法
print(hasattr(person, 'say_hello')) # True
2.3 什么时候用?
- 在调用属性/方法前检查其是否存在
- 编写通用代码,需要处理不同对象类型时
- 动态属性访问
3. 其他类似的重要函数
3.1 getattr() - 获取属性
class MyClass:
value = 100
obj = MyClass()
# 安全获取属性
print(getattr(obj, 'value')) # 100
print(getattr(obj, 'unknown', 0)) # 0 (默认值)
# 等同于 obj.value,但更安全
3.2 setattr() - 设置属性
class Person:
pass
p = Person()
setattr(p, 'name', 'Charlie') # 设置属性
setattr(p, 'age', 30)
print(p.name) # Charlie
3.3 isinstance() - 类型检查
value = "hello"
print(isinstance(value, str)) # True
print(isinstance(value, (str, int))) # True (多个类型检查)
# 比 type() 更好,考虑继承
class Animal: pass
class Dog(Animal): pass
dog = Dog()
print(isinstance(dog, Animal)) # True
print(type(dog) == Animal) # False
3.4 callable() - 检查是否可调用
def my_function():
return "Hello"
class MyClass:
def __call__(self):
return "Callable object"
print(callable(my_function)) # True
print(callable(MyClass())) # True
print(callable("hello")) # False
4. 实际应用示例
# 配置文件处理示例
config = {
'database': {
'host': 'localhost',
'port': 5432
}
}
# 安全地获取嵌套配置
db_host = config.get('database', {}).get('host', '127.0.0.1')
db_port = config.get('database', {}).get('port', 3306)
timeout = config.get('timeout', 30) # 不存在的配置使用默认值
print(f"Host: {db_host}, Port: {db_port}, Timeout: {timeout}")
# 动态方法调用示例
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
calc = Calculator()
# 根据用户输入动态调用方法
operation = input("Enter operation (add/multiply): ")
if hasattr(calc, operation):
method = getattr(calc, operation)
result = method(5, 3)
print(f"Result: {result}")
else:
print("Operation not supported")
5. 总结对比
| 函数/方法 | 作用 | 主要用途 |
|---|---|---|
.get() | 安全获取字典值 | 避免KeyError,提供默认值 |
hasattr() | 检查对象是否有属性 | 动态属性检查 |
getattr() | 获取对象属性 | 安全属性访问,支持默认值 |
setattr() | 设置对象属性 | 动态设置属性 |
isinstance() | 类型检查 | 考虑继承关系的类型判断 |
callable() | 检查是否可调用 | 判断对象是否为函数/方法 |
394

被折叠的 条评论
为什么被折叠?



