本篇文章給大家分享的內容是關於Python物件導向之擷取對象資訊,有著一定的參考價值,有需要的朋友可以參考一下
當我們拿到一個對象的引用時,如何知道這個對象是什麼類型、有哪些方法呢?
使用type()
首先,我們來判斷物件類型,使用type()函數:
基本類型都可以使用type()判斷:
>>> type(123)<class 'int'>>>> type('jeff')<class 'str'>>>> type(True)<class 'bool'>>>> type(None)<class 'NoneType'>
如果一個變數指向函數或者類,也可以用type()判斷:
>>> type(abs)<class 'builtin_function_or_method'>
但是type()函數返回的是什麼類型呢?它返回對應的Class類型。如果我們要在if語句中判斷,就需要比較兩個變數的type類型是否相同:
>>> type(123) == type(456)True>>> type('jeff') == type('1993')True>>> type('jeff') == strTrue>>> type(123) == intTrue>>> type(123) == type('jeff')False
判斷基礎資料型別 (Elementary Data Type)可以直接寫int、str等,但如果要判斷一個對象是否是函數怎麼辦?可以使用types模組中定義的常量:
>>> import types>>> def fn():... pass...>>> type(fn) == types.FunctionTypeTrue>>> type(abs) == types.BuiltinFunctionTypeTrue>>> type(lambda x:x) == types.LambdaTypeTrue>>> type((x for x in range(10))) == types.GeneratorTypeTrue
使用 isinstance()
對於class的繼承關係來說,使用type()就很不方便。我們要判斷class的類型,就可以使用isinstance()函數。
我們回顧上次的例子如果繼承關係是:
object、Animal、Dog、Husky
class Animal(object): def run(self): print('Animal is running...')class Dog(Animal): def run(self): print('Dog is haha running...') def eat(self): print('Eating meat...')class Cat(Animal): def run(self): print('Cat is miaomiao running...') def eat(self): print('Eating fish...')class Husky(Dog): def run(self): print('Husky is miaomiao running...')dog = Dog()dog.run()dog.eat()xinxin = Husky()xinxin.run()cat = Cat()cat.run()cat.eat()
Dog is haha running...Eating meat...Husky is miaomiao running...Cat is miaomiao running...Eating fish...
那麼,isinstance()就可以告訴我們,一個對象是否是某種類型。先建立3中類型的對象:
a= Animal()d = Dog()h = Husky()print(isinstance(h,Husky))print(isinstance(h,Dog))print(isinstance(h,Animal))print(isinstance(h,object))print(isinstance('a',str))print(isinstance(123,int))
TrueTrueTrueTrueTrueTrue
print(isinstance(d,Husky))False
並且還可以判斷一個變數是否是某些類型中的一種,比如下面的代碼就可以判斷是否是list或者tuple:
>>> isinstance([1,2,3],(tuple,list))True>>> isinstance((1,2,3),(tuple,list))True>>> isinstance(1,(tuple,list))False
使用dir()
如果要獲得一個對象的所有屬性和方法,可以使用dir()函數,它返回一個包含字串的list,比如,獲得一個str對象的所有屬性和方法:
>>> dir(123)['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__pmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floorp__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rpmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloorp__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruep__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truep__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']>>> dir('jeff')['__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']
>>> dir('abc') File "<stdin>", line 1 dir('abc') ^SyntaxError: invalid character in identifier注意括弧要英文下的括弧
類似__xxx__的屬性和方法再Python中都是有特殊用途的,比如__len__方法返回長度。在Python中,如果你調用len()函數試圖擷取一個對象的長度,實際上,在len()函數內部,它自動去調用該對象的__len__()方法,所以,下面的代碼是等價的:
>>> len('asd')3>>> 'asd'.__len__()3
剩下的都是普通屬性或方法,比如lower()返回小寫字串:
>>> 'ASDD'.lower()'asdd'
僅僅把屬性和方法列出來是不夠的,配合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')True>>> obj.x9>>> hasattr(obj,'y')False>>> setattr(obj,'y',19)>>> hasattr(obj,'y')True>>> getattr(obj,'y')19
如果試圖擷取不存在的屬性,會拋出AttributeError的錯誤:
>>> getattr(obj,'Z')Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'MyObject' object has no attribute 'Z'>>>
可以傳入一個default參數,如果屬性不存在,就反回預設值:
>>> getattr(obj,'Z',404)404
也可以獲得對象的方法:
>>> hasattr(obj, 'power') # 有屬性'power'嗎?True>>> getattr(obj, 'power') # 擷取屬性'power'<bound method MyObject.power of <__main__.MyObject object at0x10077a6a0>>>>> fn = getattr(obj, 'power') # 擷取屬性'power'並賦值到變數 fn>>> fn # fn 指向 obj.power<bound method MyObject.power of <__main__.MyObject object at0x10077a6a0>>>>> fn() # 調用 fn()與調用 obj.power()是一樣的81