python getattr()

object, name [ , default ] )

Return the value of the named attributed of  objectname must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example,  getattr(x, 'foobar') is equivalent to  x.foobar. If the named attribute does not exist,  default is returned if provided, otherwise  AttributeError is raised.


例子:
#!/ usr/bin/ python
#-*- conding utf-8 -*-


class  Tests(object):     #定义类
    aaa =  '10'            #定义变量

     def  test(self):      #定义类的方法test
        b =  20
         return  b

if  __name__ ==  "__main__"  :
   
    t = Tests()          #实例化

    snap1 = getattr(t,  'test' )()          #获取对象中test方法,并执行 
    snap2 = getattr(t,  'aaa'  , 'default'  )   #获取对象中相应的值,如果没有,则使用default
    snap3 = getattr(t, ' bbb' ,  'default'  )   #获取对象中相应的值,如果没有,则使用default
     print   'snap1=' ,snap1
     print   'snap2=' ,snap2
     print   'snap3='  ,snap3


输出如下
snap1= 20
snap2= 10
snap3= default
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值