1. 程式人生 > >python24 跟類相關的BIF

python24 跟類相關的BIF

none default recent delattr 默認 logs ins back ()

1. issubclass(class,classinfo)

  一個類被認為是其自身的子類

  classinfo可以是類對象組成的元組,只要class與其中任何一個候選類的子類,則返回True

  其他情況TypeError

>>> class A():
...     pass
... 
>>> class B(A):
...     pass
... 
>>> issubclass(B,A)
True
>>> issubclass(B,B)
True
>>> issubclass(A,B)
False
>>> issubclass(A,object) True

2. isinstance(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

3.hasattr(object,name)

 attr = attribute : 屬性

 測試對象是否有相應的屬性

>>> class C:
...     def __init__(self,x=0):
...             self.x = x
... 
>>> c1 = C()
>>> hasattr(c1,x)
True
>>> hasattr(c1,x)
Traceback (most recent call last):
  File "<stdin>", line 1, in
<module> NameError: name x is not defined

4.getattr(object,name[,default])

 訪問對象的屬性值,如果不存在返回設置的默認值,否則會拋出AttrubuteError

>>> getattr(c1,x)
0
>>> getattr(c1,y,您所訪問的屬性不存在...)
您所訪問的屬性不存在...

5.setattr(object,name,value)

 設置對象的屬性值,如果不存在,將創建屬性並賦值

>>> setattr(c1, x, 5)
>>> getattr(c1, x)
5
>>> setattr(c1, y, 10)
>>> getattr(c1, y)
10

6.delattr(object, name)

>>> delattr(c1,y)
>>> getattr(c1,y,訪問屬性不存在)
訪問屬性不存在

7.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.size
18
>>> c1.getSize()
18

 >>> del c1.x
 >>> c1.size
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 AttributeError: ‘C‘ object has no attribute ‘size‘

 

    

python24 跟類相關的BIF