继续获取对象和方法

305 阅读2分钟

通过dir获取对象所有属性和方法:

>>> dir('ABC')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
 '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
 '__init_subclass__', '__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__返回对象的长度。 在调用len()获取对象的长度的时候,实际上它是自动去调用该对象的__len__()方法。

使用len() 和__len__()是相同的:

>>> len('ABC')
3
>>> 'ABC'.__len__()
3

自己写类,也想使用len(myObject),可以自己写一个__len__()方法:

>>> class MyDog(object):
...     def __len__(self):
...             return 100
...
>>> dog = MyDog()
>>> len(dog)
100

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)
>>> hasattr(obj, 'y')
True
>>> getattr(obj, 'y')   #获取属性‘y’值
19
>>> obj.y    #获取属性‘y’值
19
>>>

获取不存在的属性会报错:

>>> getattr(obj, 'z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyObject' object has no attribute 'z'
>>>

当获取不存在的属性时,就输出一个值:

>>> getattr(obj, 'z', 404)
404

也可以获取方法:

>>> hasattr(obj, 'power')       #是否有 power方法
True
>>> getattr(obj, 'power')       #是否有 power属性
<bound method MyObject.power of <__main__.MyObject object at 0x000001D044B06518>>
>>> fn = getattr(obj, 'power')  #将power 属性值赋值给fn
>>> fn     #fn指向obj.power
<bound method MyObject.power of <__main__.MyObject object at 0x000001D044B06518>>
>>> fn()   #调用fn() 相当于调用 obj.power() 是一样的
81
>>>

注意点: 只有不知道对象的信息的时候,才需要获取对象信息。如果我们可以直接写:

sum = obj.x + obj.y

就不要写成:

sum = getattr(obj, 'x') + getattr(obj, 'y')

总结:

1、通过dir() 获取对象的属性和方法
2、通过setattr(),getattr(),hasattr() 改变,获取,判断 对象的属性和方法