首页Python【Python内置函数】h...

【Python内置函数】hasattr()函数

Python 提供了许多内置函数,这些函数是Python语言的一部分,可以直接在Python程序中使用而无需导入任何模块。

本系列将会陆续整理分享一些的Python内置函数。

文章配套代码获取有以下两种途径:
  • 通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj 提取码:mnsj
  • 前往GitHub获取
https://github.com/returu/Python_built-in_functions





01
简介

hasattr()函数用于检查一个对象是否具有某个属性或方法,无论这些属性和方法是静态定义的,还是动态添加的,或者是继承而来的。hasattr()通过调用getattr(object, name)来实现其功能,并观察是否会引发AttributeError异常。
hasattr() 函数适用于不确定对象结构的场景,如处理第三方库对象或动态生成的类。hasattr() 函数不仅检查对象自身的属性,还会考虑继承链中的属性和方法。

hasattr() 函数的基本语法如下:

hasattr(object, name)
参数说明:
  • object:要检查的对象;
  • name:要检查的属性或方法的名称,必须是字符串类型,否则会抛出 TypeError

返回值:

如果对象具有指定的属性或方法,返回 True则返回 False

02
使用

下面是一些使用 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:继承属性
hasattr()不仅检查对象自身的属性,还会检查继承链中的属性和方法。
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


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

RELATED ARTICLES

欢迎留下您的宝贵建议

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments