十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
了解Shuttle類怎樣在python3中生成?這個問題可能是我們?nèi)粘W習或工作經(jīng)常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!
如果你想模擬一個航天飛船,你可能要寫一個新的類。但是航天飛機是火箭的一種特殊形式。你可以繼承 Rocket 類,添加一些新的屬性和方法,生成一個 Shuttle 類而不是新建一個類。
航天飛船的一個重要特性是他可以重用。因此我們添加記錄航天飛船服役的次數(shù)。其他基本和 Rocket 類相同。
實現(xiàn)一個 Shuttle 類,如下所示:
from math import sqrt class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_rocket(self, x_increment=0, y_increment=1): # Move the rocket according to the paremeters given. # Default behavior is to move the rocket up one unit. self.x += x_increment self.y += y_increment def get_distance(self, other_rocket): # Calculates the distance from this rocket to another rocket, # and returns that value. distance = sqrt((self.x-other_rocket.x)**2+(self.y-other_rocket.y)**2) return distance class Shuttle(Rocket): # Shuttle simulates a space shuttle, which is really # just a reusable rocket. def __init__(self, x=0, y=0, flights_completed=0): super().__init__(x, y) self.flights_completed = flights_completed shuttle = Shuttle(10,0,3) print(shuttle)
當一個子類要繼承父類時,在定義子類的圓括號中填寫父類的類名:
class NewClass(ParentClass):
新類的 __init__() 函數(shù)需要調(diào)用新類的 __init__() 函數(shù)。新類的 __init__() 函數(shù)接受的參數(shù)需要傳遞給父類的 __init__() 函數(shù)。由 super().__init__() 函數(shù)負責:
class NewClass(ParentClass): def __init__(self, arguments_new_class, arguments_parent_class): super().__init__(arguments_parent_class) # Code for initializing an object of the new class.
super()函數(shù)會自動將self參數(shù)傳遞給父類。你也可以通過用父類的名字實現(xiàn),但是需要手動傳遞self參數(shù)。如下所示:
class Shuttle(Rocket): # Shuttle simulates a space shuttle, which is really # just a reusable rocket. def __init__(self, x=0, y=0, flights_completed=0): Rocket.__init__(self, x, y) self.flights_completed = flights_completed
這樣寫看起來可讀性更高,但是我們更傾向于用 super() 的語法。當你使用 super() 的時候,不必關心父類的名字,以后有改變時會變得更加靈活。而且隨著繼承的學習,以后可能會出現(xiàn)一個子類繼承自多個父類的情況,使用 super() 語法就可以在一行內(nèi)調(diào)用所有父類的 __init__() 方法。
感謝各位的閱讀!看完上述內(nèi)容,你們對Shuttle類怎樣在python3中生成大概了解了嗎?希望文章內(nèi)容對大家有所幫助。如果想了解更多相關文章內(nèi)容,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。