本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
hasattr(object, name)
-
object:要检查的对象; -
name:要检查的属性或方法的名称,必须是字符串类型,否则会抛出 TypeError。
返回值:
下面是一些使用 hasattr() 函数的示例:
-
示例 1:基本使用
class Person:
def __init__(self):
self.name = "Alice"
def greet(self):
return f"Hello, my name is {self.name}."
obj = Person()
# 检查对象是否有属性 'name'
print(hasattr(obj, 'name')) # 输出: True
# 检查对象是否有属性 'age'
print(hasattr(obj, 'age')) # 输出: False
# 检查对象是否有方法 'greet'
print(hasattr(obj, 'greet')) # 输出: True
# 检查对象是否有方法 '__init__'
print(hasattr(obj, '__init__')) # 输出: True
-
示例 2:动态属性
如果对象的属性是动态添加的,hasattr() 同样可以检测到。
class MyClass:
def __init__(self):
self.name = "Alice"
obj = MyClass()
# 动态添加属性
obj.age = 25
# 检查动态添加的属性
print(hasattr(obj, 'age')) # 输出: True
-
示例 3:继承属性
class ParentClass:
def __init__(self):
self.parent_name = "Parent"
class ChildClass(ParentClass):
def __init__(self):
super().__init__()
self.child_name = "Child"
obj = ChildClass()
# 检查继承的属性
print(hasattr(obj, 'parent_name')) # 输出: True
# 检查子类自己的属性
print(hasattr(obj, 'child_name')) # 输出: True
-
示例 4:触发属性获取
hasattr()函数内部通过调用getattr()函数实现,可能触发属性描述符(如@property)的副作用。
例如,下面的示例中当调用hasattr()时,因为hasattr()内部会尝试获取该属性,这时候@property装饰的属性在被访问时会执行对应的getter方法。所以会打印出“正在加载数据…”,并且返回True,因为该属性存在。
class User:
@property
def data(self):
print("正在加载数据...") # 副作用:执行了某些操作
return [1, 2, 3]
user = User()
print(hasattr(user, "data")) # 输出:正在加载数据... → True


本篇文章来源于微信公众号: 码农设计师