python之函数用法getattr()

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#python之函数用法getattr()



#getattr()
#说明:
'''
getattr(...)
    getattr(object, name[, default]) -> value
    default:默认值
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
'''



#案例
class A():
    
    def __init__(self):   
        self.a = 'a'
        
    def method(self):   
        #print "method print"
        return 'xiaodeng'

a = A()
#如果有属性a则打印a,否则打印default
print getattr(a, 'a', 'default')        #a


#如果有属性b则打印b,否则打印default 
print getattr(a, 'b', 'default')        #default


#如果有方法method,否则打印其地址,否则打印default
print getattr(a, 'method', 'default')   #<bound method A.method of <__main__.A instance>>


#如果有方法method,运行函数并打印None否则打印default
print getattr(a, 'test', 'default')     #default  

 

posted @ 2015-11-07 21:33  Xiao|Deng  阅读(452)  评论(0编辑  收藏  举报