Advertisement

关于hasattr()、getattr()、setattr()函数的使用

阅读量:

当我们定义一个类及其相关对象时

  • hasattr()
  • getattr()
  • setattr()
为了举例说明,先定义一个类
复制代码
    class DP(object):
    
    """process data"""
    
    def __init__(self,root=None,file_name=None,is_load=True):
    
        self._root=root
        self._file_name=file_name
        self._is_load=is_load
        self._data=None
1.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

举例说明:

复制代码
    dp=DP()
    if hasattr(dp,'_root'):
    print(True)
    else:
       print(False)

结果是:True

2.getattr():获取对象的某属性的值
复制代码
    源码:
    def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass

举例说明:

复制代码
    当我们选择默认值时:
    	dp=DP()
    	print(getattr(dp,'_root'))
    结果是:None
    
    当我们定义对象时,设置属性值:
       dp=DP(root='PATH')
       print(getattr(dp,'_root'))
     结果是:PATH

当对象缺乏预先定义的属性名时

复制代码
    源码:
    def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.    
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass

举例说明:

复制代码
    dp=DP()
    #判断是否有某个属性,如果没有,则为对象设置相应的属性
    if hasattr(dp,'_dir'):
    print(True)
    else:
       setattr(dp,'_dir','random_value')

全部评论 (0)

还没有任何评论哟~