40.類和物件:一些相關的BIF
阿新 • • 發佈:2019-02-15
一些相關BIF
issubclass(class, classing)
用來判斷類引數class是否是型別引數classinfo的子類
>>> class A:
pass
>>> class B(A):
pass
>>> issubclass(B, A)
True
>>> issubclass(B, B)
True
>>> is subclass(B, object)
True
>>> class C:
pass
>>> issubclass(B, C)
False
isinstance(object, classinfo)
判斷 object 是否為 classinfo 的實體
1. 如果第一個引數不是物件,則永遠返回False
2. 如果第二個引數不是類或者由類物件組成的元祖,
會丟擲一個TypeError異常
>>> b1 = B()
>>> isinstance(b1, B)
True
>>> isinstance(b1, A)
True
>>> isinstance(b1, C)
False
>>> isinstance(b1, (A,B,C))
True
hasattr(object, name)
判斷 name 是否為 object 的屬性名稱
attire = attribute:屬性
>>> class C:
def __init__(self, x=0):
self.x = x
>>> c1 = C()
>>> hasattr(c1, 'x')
True
getattr(object, name[, default])
如果存在name屬性(方法)則返回name的值(方法地址)否則返回default值。
>>> getattr(c1, 'x')
0
>>> getattr(c1, 'y')
Traceback (most recent call last):
......
AttributeError: 'C' object has no attribute 'y'
>>> getattr(c1, 'y', '您所訪問的屬性不存在...')
'您所訪問的屬性不存在...'
setattr(object, name, value)
設定物件 object 的新屬性
>>> setattr(c1, 'y', 'kuangren')
>>> getattr(c1, 'y', '您所訪問的屬性不存在...')
'kuangren'
delattr(object, name)
該函式刪除該obj的一個由string指定的屬性
>>> delattr(c1, 'y')
>>> delattr(c1, 'y')
Traceback (most recent call last):
File '<pyshell#31>', line 1, in <module>
delattr(c1, 'y')
AttributeError: y
property(fget=None, fset=None, fdel=None, doc=None)
>>> class C:
def __init__(self, size=10):
self.size = size
def getSize(self):
return self.size
def setSize(self, value):
self.size = value
def delSize(self):
del self.size
x = property(getSize, setSize, delSize)
>>> c1 = C()
>>> c1.getSize()
10
>>> c1.x
10
>>> c1.x = 18
>>> c1.x
18
>>> c1.getsize()
18
>>> del c1.x
>>> c1.size
Traceback (most recent call last):
...
AttributeError: 'C' object has no attribute 'size'