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)

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐