getattr() 函数用于返回一个对象属性值:
getattr(object, name[, default])
class InfoCollection(object):
    def collect(self): 
        # 根据平台的不同,执行不同的方法
        try:
            func = getattr(self, platform.system())
            info_data = func()
        except AttributeError:
            sys.exit("不支持当前操作系统: [%s]! " % platform.system())
    def Linux(self):
        return linux_sys_info()
    def Windows(self):
        return windows_sys_info()
例如脚本不支持Mac系统,当在Mac上运行时会报AttributeError错误并输出当前的系统平台:Darwin
文档信息
- 本文作者:zhupite
- 本文链接:https://zhupite.com/python/python-getattr.html
- 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)