继续获取对象和方法
通過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() 改變,獲取,判斷 對象的屬性和方法復制代碼轉載于:https://juejin.im/post/5ad8a27cf265da0ba2668576
總結
- 上一篇: 云计算逼迫运营商重新出海
- 下一篇: opatch更新