首頁  >  文章  >  後端開發  >  Python物件導向之獲取物件訊息

Python物件導向之獲取物件訊息

不言
不言原創
2018-04-14 10:28:111590瀏覽

本篇文章給大家分享的內容是關於Python物件導向之獲取物件訊息,有著一定的參考價值,有需要的朋友可以參考一下

當我們拿到一個物件的引用時,如何知道這個物件是什麼類型、有哪些方法呢?

使用type()

首先,我們來判斷物件類型,使用type()函數:

基本類型都可以使用type()判斷:

>>> type(123)
<class &#39;int&#39;>
>>> type(&#39;jeff&#39;)
<class &#39;str&#39;>
>>> type(True)
<class &#39;bool&#39;>
>>> type(None)
<class &#39;NoneType&#39;>

如果一個變數指向函數或類,也可以用type()判斷:

>>> type(abs)
<class &#39;builtin_function_or_method&#39;>

但是type()函數回傳的是什麼型別呢?它會傳回對應的Class類型。如果我們要在if語句中判斷,就需要比較兩個變數的type型別是否相同:

>>> type(123) == type(456)
True
>>> type(&#39;jeff&#39;) == type(&#39;1993&#39;)
True
>>> type(&#39;jeff&#39;) == str
True
>>> type(123) == int
True
>>> type(123) == type(&#39;jeff&#39;)
False

判斷基本資料型別可以直接寫int、str等,但如果要判斷一個物件是否是函數怎麼辦?可以使用types模組中定義的常數:

>>> import types
>>> def fn():
...     pass
...
>>> type(fn) == types.FunctionType
True
>>> type(abs) == types.BuiltinFunctionType
True
>>> type(lambda x:x) == types.LambdaType
True
>>> type((x for x in range(10))) == types.GeneratorType
True

使用 isinstance()

對於class的繼承關係來說,使用type()就很不方便。我們要判斷class的類型,就可以使用isinstance()函數。

我們回顧上次的例子如果繼承關係是:

object、Animal、Dog、Husky

class Animal(object):
    def run(self):
        print(&#39;Animal is running...&#39;)

class Dog(Animal):
    def run(self):
        print(&#39;Dog is haha running...&#39;)

    def eat(self):
        print(&#39;Eating meat...&#39;)
class Cat(Animal):
    def run(self):
        print(&#39;Cat is miaomiao running...&#39;)

    def eat(self):
        print(&#39;Eating fish...&#39;)
class Husky(Dog):
    def run(self):
        print(&#39;Husky is miaomiao running...&#39;)
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(&#39;a&#39;,str))
print(isinstance(123,int))
True
True
True
True
True
True
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)
[&#39;__abs__&#39;, &#39;__add__&#39;, &#39;__and__&#39;, &#39;__bool__&#39;, &#39;__ceil__&#39;, &#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__pmod__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__float__&#39;, &#39;__floor__&#39;, &#39;__floorp__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__index__&#39;, &#39;__init__&#39;, &#39;__int__&#39;, &#39;__invert__&#39;, &#39;__le__&#39;, &#39;__lshift__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__neg__&#39;, &#39;__new__&#39;, &#39;__or__&#39;, &#39;__pos__&#39;, &#39;__pow__&#39;, &#39;__radd__&#39;, &#39;__rand__&#39;, &#39;__rpmod__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rfloorp__&#39;, &#39;__rlshift__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__ror__&#39;, &#39;__round__&#39;, &#39;__rpow__&#39;, &#39;__rrshift__&#39;, &#39;__rshift__&#39;, &#39;__rsub__&#39;, &#39;__rtruep__&#39;, &#39;__rxor__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__sub__&#39;, &#39;__subclasshook__&#39;, &#39;__truep__&#39;, &#39;__trunc__&#39;, &#39;__xor__&#39;, &#39;bit_length&#39;, &#39;conjugate&#39;, &#39;denominator&#39;, &#39;from_bytes&#39;, &#39;imag&#39;, &#39;numerator&#39;, &#39;real&#39;, &#39;to_bytes&#39;]
>>> dir(&#39;jeff&#39;)
[&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getitem__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__iter__&#39;, &#39;__le__&#39;, &#39;__len__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasshook__&#39;, &#39;capitalize&#39;, &#39;casefold&#39;, &#39;center&#39;, &#39;count&#39;, &#39;encode&#39;, &#39;endswith&#39;, &#39;expandtabs&#39;, &#39;find&#39;, &#39;format&#39;, &#39;format_map&#39;, &#39;index&#39;, &#39;isalnum&#39;, &#39;isalpha&#39;, &#39;isdecimal&#39;, &#39;isdigit&#39;, &#39;isidentifier&#39;, &#39;islower&#39;, &#39;isnumeric&#39;, &#39;isprintable&#39;, &#39;isspace&#39;, &#39;istitle&#39;, &#39;isupper&#39;, &#39;join&#39;, &#39;ljust&#39;, &#39;lower&#39;, &#39;lstrip&#39;, &#39;maketrans&#39;, &#39;partition&#39;, &#39;replace&#39;, &#39;rfind&#39;, &#39;rindex&#39;, &#39;rjust&#39;, &#39;rpartition&#39;, &#39;rsplit&#39;, &#39;rstrip&#39;, &#39;split&#39;, &#39;splitlines&#39;, &#39;startswith&#39;, &#39;strip&#39;, &#39;swapcase&#39;, &#39;title&#39;, &#39;translate&#39;, &#39;upper&#39;, &#39;zfill&#39;]
>>> dir(&#39;abc&#39;)  File "<stdin>", line 1
    dir(&#39;abc&#39;)
       ^
SyntaxError: invalid character in identifier注意括号要英文下的括号

類似__xxx__的屬性和方法再Python中都是有特殊用途的,例如__len__方法返回長度。在Python中,如果你呼叫len()函數試圖取得一個物件的長度,實際上,在len()函數內部,它會自動去呼叫該物件的__len__()方法,所以,下面的程式碼是等價的:

>>> len(&#39;asd&#39;)
3
>>> &#39;asd&#39;.__len__()
3

剩下的都是普通屬性或方法,例如lower()返回小寫的字串:

>>> &#39;ASDD&#39;.lower()
&#39;asdd&#39;

僅僅把屬性和方法列出來是不夠的,配合getattr() 、setattr()以及hasattr(),我們可以直接操作一個物件的狀態:

>>> class MyObject(object):
...     def __init__(self):
...         self.x = 9
...     def power(self):
...         return self.x*self.x
>>>
>>> obj = MyObject()
>>> hasattr(obj,&#39;x&#39;)
True
>>> obj.x
9
>>> hasattr(obj,&#39;y&#39;)
False
>>> setattr(obj,&#39;y&#39;,19)
>>> hasattr(obj,&#39;y&#39;)
True
>>> getattr(obj,&#39;y&#39;)
19

如果試圖取得不存在的屬性,會拋出AttributeError的錯誤:

>>> getattr(obj,&#39;Z&#39;)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: &#39;MyObject&#39; object has no attribute &#39;Z&#39;
>>>

可以傳入一個default參數,如果屬性不存在,就反回預設值:

>>> getattr(obj,&#39;Z&#39;,404)
404

也可以取得物件的方法:

>>> hasattr(obj, &#39;power&#39;) # 有属性&#39;power&#39;吗?
True
>>> getattr(obj, &#39;power&#39;) # 获取属性&#39;power&#39;
<bound method MyObject.power of <__main__.MyObject object at
0x10077a6a0>>
>>> fn = getattr(obj, &#39;power&#39;) # 获取属性&#39;power&#39;并赋值到变量 fn
>>> fn # fn 指向 obj.power
<bound method MyObject.power of <__main__.MyObject object at
0x10077a6a0>>
>>> fn() # 调用 fn()与调用 obj.power()是一样的
81

相關推薦:

Python物件導向之繼承與多型別

Python物件導向存取限制

Python物件導向之類與實例














## #################

以上是Python物件導向之獲取物件訊息的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn