1. 程式人生 > >Python物件相關內建函式

Python物件相關內建函式

針對一個物件,通過以下幾個函式,可以獲取到該物件的一些資訊。

 

1、type() ,返回某個值的型別

 

>>> type(123)
<class 'int'>
>>> type('str')
<class 'str'>
>>> type(None)
<type(None) 'NoneType'>

使用就是括號里加引數,返回這個引數屬於的類

123 是int類  'str'是 str類,None是NoneType類

>>> type(123
)==type(456) True >>> type(123)==int True >>> type('abc')==type('123') True >>> type('abc')==str True >>> type('abc')==type(123) False

 

 

2、isinstance()  返回某個值是否是某個類

class Animal(object):
    pass

class Dog(Animal):
    pass

class Husky(Dog):
    pass

h 
= Husky() print('h是不是Animal類:',isinstance(h,Animal)) print('h是不是Dog類:',isinstance(h,Dog)) print('h是不是Husky類:',isinstance(h,Husky)) ------------------------------------------------------- h是不是Animal類: True h是不是Dog類: True h是不是Husky類: True

 

基本型別類似:

>>> isinstance('a', str)
True
>>> isinstance(123, int) True >>> isinstance(b'a', bytes) True

 

判斷一個變數是否是某些型別中的一種,比如下面的程式碼就可以判斷是否是list或者tuple:

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

 

 

3、dir()  獲得一個物件的所有屬性和方法 ,返回一個包含字串的list ,一個str物件的所有屬性和方法

>>> dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']

 

判斷物件是否有某個屬性(函式,屬性)

>>> 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) # 設定一個屬性'y'
>>> hasattr(obj, 'y') # 有屬性'y'嗎?
True
>>> getattr(obj, 'y') # 獲取屬性'y'
19
>>> obj.y # 獲取屬性'y'
19

----------------------------------------------------

如果試圖獲取不存在的屬性,會丟擲AttributeError的錯誤:

>>> getattr(obj, 'z') # 獲取屬性'z'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyObject' object has no attribute 'z'
可以傳入一個default引數,如果屬性不存在,就返回預設值:

>>> getattr(obj, 'z', 404) # 獲取屬性'z',如果不存在,返回預設值404
404

 

 

也可以獲得物件的方法:

>>> hasattr(obj, 'power') # 有屬性'power'嗎?
True
>>> getattr(obj, 'power') # 獲取屬性'power'
<bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
>>> fn = getattr(obj, 'power') # 獲取屬性'power'並賦值到變數fn
>>> fn # fn指向obj.power
<bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
>>> fn() # 呼叫fn()與呼叫obj.power()是一樣的
81