1. 程式人生 > >python 學習彙總47:class類型別判斷(基礎學習- 推薦 tcy)

python 學習彙總47:class類型別判斷(基礎學習- 推薦 tcy)

類判斷  2018/11/17 

1.定義類:

__metaclass__ = type # 確定使新式類
class father():
def __init__(self,x0=None,x=None,y=None):
self.x0 = x0
self.x=x
self.y=y
def show(self):
print("father()已經建立",self.x0,self.x,self.y)


class son(father):
def __init__(self,x0=100,x=200,y=300):
super(son, self).__init__(x0,x,y)
self.x0=-3
def show1(self):
print("son()已經建立",self.x0)#如果父類有此屬性,被初始化為-3

s0 = son()
f0=father()

2.檢視類的子類:

2.1檢視類的子類
#__subclasses__不能是例項物件
print('1',father.__subclasses__())#[<class '__main__.son'>]
print('1',son.__subclasses__()) #[]
2.2檢視類的父類
#__bases__不能是例項物件
print('2',father.__bases__) #(<class 'object'>,)
print('2',son.__bases__)     # (<class '__main__.father'>,)
2.3type檢視類
print('3',type(father),type(son),type(f0),type(s0))
        # <class 'type'> # < class 'type' >
        # < class '__main__.father' > # < class '__main__.son' >

print('3',father.__class__,son.__class__,f0.__class__,s0.__class__)
        # <class 'type'> # < class 'type' >
        # < class '__main__.father' > # < class '__main__.son' >

print('3',father.mro(),son.mro())
        # [<class '__main__.father'>, <class 'object'>]
        # <class '__main__.son'>, <class '__main__.father'>, <class 'object'> 
3.判斷父子類
#issubclass引數必須是類,不能為例項
print('4',issubclass(son, father)) #True

#i__subclasscheck__必須是類,不能為例項
print("5.",father.__subclasscheck__(son))#True
4.類的例項判斷
print("6.",isinstance(s0, son))    #True
print("6.",isinstance(s0, father)) # True