python内置方法、模块讲解(十一)

  • 2016-03-11 23:06:21
  • 1240
  • 0

三十二、getattr方法

1、定义:

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.

2、解释:从一个对象得到一个已定义的属性即:object.name, 此方法与前面讲的delattr是类似,属一个系列的。

3、举例:

>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
>>> getattr(datetime, 'time')
<type 'datetime.time'>
>>> getattr(datetime, 'a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'a'
>>> getattr(datetime, 'a', 'unnamed')
'unnamed'

三十三、globals方法

1、定义:

globals(...)
    globals() -> dictionary

    Return the dictionary containing the current scope's global variables.

2、解释:返回一个包含当前全局变量的字典

3、举例:

>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'datetime': <module 'datetime' (built-in)>, '__doc__': None, '__package__': None}
>>> import time
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, 'datetime': <module 'datetime' (built-in)>, 'time': <module 'time' (built-in)>, '__name__': '__main__', '__package__': None, '__doc__': None}

 


发表评论

* *