使用dir()

    如果要获得一个对象的所有属性和方法,可以使用 dir() 函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:

    >>> dir('ABC')

    ['add', 'class', 'contains', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'getnewargs', 'gt', 'hash', 'init', 'iter', 'le', 'len', 'lt', 'mod', 'mul', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'rmod', 'rmul', 'setattr', 'sizeof', 'str', 'subclasshook', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

    类似 xxx 的属性和方法在Python中都是有特殊用途的,比如 len 方法返回长度。在Python中,如果你调用 len() 函数试图获取一个对象的长度,实际上,在 len() 函数内部,它自动去调用该对象的 len() 方法,所以,下面的代码是等价的:

    >>> len('ABC')

    3

    >>> 'ABC'.len()

    3

    我们自己写的类,如果也想用 len(myObj) 的话,就自己写一个 len() 方法:

    >>> class MyDog(object):

    … def len(self):

    … return 100



    >>> dog = MyDog()

    >>> len(dog)

    100

    剩下的都是普通属性或方法,比如 lower() 返回小写的字符串:

    >>> 'ABC'.lower()

    'abc'

    仅仅把属性和方法列出来是不够的,配合 getattr() setattr() 以及 hasattr() ,我们可以直接操作一个对象的状态:

    >>> class MyObject(object):

    … def init(self):

    … self.x = 9

    … def power(self):

    … return self.x * self.x



    >>> obj = MyObject()

    紧接着,可以测试该对象的属性:

    >>> hasattr(obj, 'x') # 有属性'x'吗?

    True

    >>> obj.x

    9

    >>> hasattr(obj, 'y') # 有属性'y'吗?

    False

    >>> setattr(obj, 'y', 19) # 设置一个属性'y'

    >>> hasattr(obj, 'y') # 有属性'y'吗?

    True

    >>> getattr(obj, 'y') # 获取属性'y'

    19

    >>> obj.y # 获取属性'y'

    19

    如果试图获取不存在的属性,会抛出AttributeError的错误:

    >>> getattr(obj, 'z') # 获取属性'z'

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    AttributeError: 'MyObject' object has no attribute 'z'

    可以传入一个default参数,如果属性不存在,就返回默认值:

    >>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404

    404

    也可以获得对象的方法:

    >>> hasattr(obj, 'power') # 有属性'power'吗?

    True

    >>> getattr(obj, 'power') # 获取属性'power'

    <bound method MyObject.power of <main.MyObject object at 0x10077a6a0>>

    >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn

    >>> fn # fn指向obj.power

    <bound method MyObject.power of <main.MyObject object at 0x10077a6a0>>

    >>> fn() # 调用fn()与调用obj.power()是一样的

    81