python when函数_python内置函数5-getattr()

Help on built-in function getattr in module __builtin__:

getattr(...)

getattr(object, name[, default]) -> value

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.

getattr(object, name[, default])

Return the value of the named attribute of object. name 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.

中文说明:

实现反射机制,可以通过字符串获取方法实例。

本函数实现获取对象object的属性,属性由name来表示,就是属性名称的字符串。

参数default是可选的参数,当获取对象的属性不存在时,就返回此值;如果没有提供此参数,同时在对象属性里也找不到,不会抛出异常AttributeError。

class A:

def __init__(self):

self.a = 'a'

def method(self):

print "method print"

a = A()

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

a

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

default

print getattr(a, 'method', 'default')   #如果有方法method,否则打印其地址,否则打印default

>

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

method print

None

>>> class Foo:

...     def __init__(self):

...             self.x=100

...

>>> foo=Foo()

>>> print(getattr(foo,'x'))

100

>>> print(foo.x)

100

>>> print(getattr(foo,'y',200))

200

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值