微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python hasattr, getattr, modules判断模块属性是否存在

hasattr菜鸟实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Coordinate:
    x = 10
    y = -5
    z = 0
 
point1 = Coordinate() 
print(hasattr(point1,'x'))
print(hasattr(point1,'y'))
print(hasattr(point1,'z'))
print(hasattr(point1,'no'))  # 没有该属性

结果:

True
True
True
False

 

getattr菜鸟实例:

>>>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
>>>

 

开源项目实例:

from sys import modules

# UserDB is the default auth_class
        authname = auth.UserDB                              #UserDB为类对象
 
        # Is the auth_class defined in the config file?      
        if self.cfg.has_option('honeypot','auth_class'):         #包含auth_class值:UserDB
            authclass = self.cfg.get('honeypot','auth_class')
            authmodule = "cowrie.core.auth"

            # Check if authclass exists in this module
            if hasattr(modules[authmodule],authclass):              #模块中有此
                authname = getattr(modules[authmodule],authclass)
            else:
                log.msg('auth_class: %s not found in %s' %
                    (authclass,authmodule))

        theauth = authname(self.cfg)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐