您当前的位置: 首页 >  Python

IT之一小佬

暂无认证

  • 1浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

python中hasattr()函数用法详解

IT之一小佬 发布时间:2022-08-01 22:34:14 ,浏览量:1

hasattr() 函数用来判断某个类实例对象是否包含指定名称的属性或方法。

  • 无论是属性名还是方法名,都在 hasattr() 函数的匹配范围内。
  • 通过该函数判断实例对象是否包含该名称的属性或方法,但不能精确判断,该名称代表的是属性还是方法。

hasattr() 函数源码如下:

def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass

语法格式如下:

hasattr(obj, name)
  • obj 指的是某个类的实例对象
  • name 表示指定的属性名或方法名
  • return    True 或者 False

示例代码:

class Test(object):
    def __init__(self):
        self.name = "张三"
        self.age = 25

    def say(self):
        print("I love study!")


obj = Test()
print(hasattr(obj, "name"))
print(hasattr(obj, "age"))
print(hasattr(obj, "say"))
print(hasattr(obj, "new_name"))

运行结果:

关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.0438s