python-getattr() 函数 dir() 函数

python-getattr() 函数

描述

getattr() 函数用于返回一个对象属性值。

语法

getattr(object, name[, default])

参数

参数
object -- 对象。
name -- 字符串,对象属性。
default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。

返回值

返回对象属性值。

实例

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, 'bar')        # 获取属性 bar 值
1
>>> getattr(a, 'bar2')       # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3)    # 属性 bar2 不存在,但设置了默认值
3

Python dir() 函数

dir函数

  • dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;
  • 带参数时,返回参数的属性、方法列表。
  • 如果参数包含方法__dir__(),该方法将被调用。
  • 如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

语法:

dir([object])
  • object -- 对象、变量、类型。

  • 返回值: 返回模块的属性列表。

示例

>>>dir()   #  获得当前模块的属性列表
['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
>>> dir([ ])    # 查看列表的方法
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
原文地址:https://www.cnblogs.com/zhangtao-0001/p/14860741.html