繼承(2)

繼承

Posted by 劉啟仲 on Monday, December 21, 2020

python中,所有東西都是物件,每個物件都有他自己的型別(type)。

# parent class / base class
class Transportation:
    def __init__(self):
        self.exterior = "white"
    def drive(self):
        print("drive method is called.")
 
# child class / deroved class
class Car(Transportation):
    def move(self):
        print("move is method called.")
        
# child class / deroved class
class Airplane(Transportation):
    def fly(self):
        print("fly method is called.")
        
toyota = Car()
toyota.drive() # drive method is called.
print(toyota.exterior) # white

isinstance( )與type( )區別:

type( )不會認為子類是一種父類類型,不考慮繼承關係。

isinstance( )會認為子類是一種父類類型,考慮繼承關係。

如果要判斷兩個類型是否相同推薦使用isinstance( )。

print(isinstance(toyota, Car)) # True
print(isinstance(toyota, Transportation)) # True
print(type(toyota)) # <class '__main__.toyota'>
print(type(Car)) # <class 'type'>

class是type的實例,type 可以創造出 class 的實例,也就是說 type 本身的型別就是type。

# class SportsCar(Transportation)
# 	pass
SportsCar = type( 'SportsCar', (Transportation,), {})
car = SportsCar()
print(type(car)) # <class '__main__.SportsCar'>

type是object的實例

print(isinstance(Car, type)) # True
print(isinstance(type, object)) # True
print(isinstance(Car, object)) # True

object( ) -> type( ) -> class( ) - >toyota( )

參考:淺談 Python Metaclass