Python 物件導向-擷取對象資訊 type isinstance getattr setattr hasattr

來源:互聯網
上載者:User

Python 物件導向-擷取對象資訊 type isinstance getattr setattr hasattr

一、type()函數

判斷基礎資料型別 (Elementary Data Type)可以直接寫intstr等:

>>> class Animal(object):
...    pass
...
>>> type(123)
<class 'int'>
>>> type('123')
<class 'str'>
>>> type(None)
<class 'NoneType'>
>>> type(abs)
<class 'builtin_function_or_method'>
>>> type(Animal())
<class '__main__.Animal'>

 

 >>> type(123) == type(456)
True
>>> type(123) == int
True

判斷一個對象是否是函數:

>>> 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()函數。

>>> class Animal(object):
...    pass
...
>>> class Dog(Animal):
...    pass
...
>>> d = Dog()
>>> isinstance(d, Dog)
True
>>> isinstance(d, Animal)
True

用isinstance()判斷基本類型:

1 >>> isinstance('a', str)2 True3 >>> isinstance(123, int)4 True5 >>> isinstance(b'a', bytes)6 True

並且還可以判斷一個變數是否是某些類型中的一種,比如下面的代碼就可以判斷是否是list或者tuple:

1 >>> isinstance([1, 2, 3], (list, tuple))2 True3 >>> isinstance((1, 2, 3), (list, tuple))4 True

優先使用isinstance()判斷類型,可以將指定類型及其子類“一網打盡”。

三、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__()方法,所以,下面的代碼是等價的:

1 >>> len('abc')2 33 >>> 'abc'.__len__()4 3

自己寫的類,如果也想用len(myObj)的話,就自己寫一個__len__()方法:

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

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

1 >>> 'abc'.upper()2 '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')
True
>>> hasattr(obj, 'y')
False
>>>
>>> setattr(obj, 'y', 20)
>>> hasattr(obj, 'y')
True
>>> getattr(obj, 'y')
20
>>> getattr(obj, 'z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyObject' object has no attribute 'z'
>>> getattr(obj, 'z', 100)    # 指定預設值
100

測試該對象的方法:

>>> hasattr(obj, 'power')
True
>>> getattr(obj, 'power')
<bound method MyObject.power of <__main__.MyObject object at 0x1014be400>>
>>> fn = getattr(obj, 'power')
>>> fn
<bound method MyObject.power of <__main__.MyObject object at 0x1014be400>>
>>> fn()
81

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.