'hasattr(object,name)'在这段代码中的含义是什么?

时间:2017-10-06 03:48:25

标签: python

我正在阅读一个经验代码并得到一些疑问。这是代码:

class EventLoop(object):
def __init__(self):
    if hasattr(select, 'epoll'):
        self._impl = select.epoll(hasattr(object, name))
        model = 'epoll'
    elif hasattr(select, 'kqueue'):
        self._impl = KqueueLoop()
        model = 'kqueue'
    elif hasattr(select, 'select'):
        self._impl = SelectLoop()
        model = 'select'
    else:
        raise Exception('can not find any available functions in select '
                        'package')

引用documentation,方法是'select.epoll([sizehint = -1])'。但在这种情况下,'hasattr(object,name)'在这段代码中是什么意思?我找不到变量'name'的声明。

1 个答案:

答案 0 :(得分:1)

python中的

hasattr(object,name)检查某个对象是否具有名为name的属性。

在这种情况下,它检查模块select是否具有文档中列出的属性之一(函数也是属性)。

这样做是为了找到此平台上可用的最佳I / O完成实现。

并非模块中的所有功能都可以同时使用,因此可能不会出现在模块中(参见module documentation):

  • epoll - 根据文档Only supported on Linux 2.5.44 and newer
  • poll - 根据文档Not supported by all operating systems
  • kqueue - 根据文档Only supported on BSD
  • select - 应该随处可用。

E.g。如果epoll可用,则会优先考虑,如果epoll不可用poll,则kqueue,最后select

即使select不可用,也会引发Exception

添加hasattr

的具体示例
  • 动词:hasattr
  • 其中:object来研究
  • 什么:属性的name(例如字符串)

# attribute of object of type string
obj = "some string"
print(hasattr(obj, 'find')) # True
print(hasattr(obj, 'nonexistentattr')) # False

# attribute of a module `math`
import math
# Check directly
print(hasattr(math, 'cos')) # True
# ...or check via variable
obj = math # obj is now a module
print(hasattr(obj, 'cos')) # True