欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 中多態(tài)性的示例和類的繼承多態(tài)性詳解

 更新時間:2023年10月28日 09:44:21   作者:返回主頁小萬哥的博客圓子  
多態(tài)性通常在類的方法中使用,其中我們可以具有相同方法名稱的多個類,本文給大家介紹Python 中多態(tài)性的示例和類的繼承多態(tài)性詳解,需要的朋友可以參考下

單詞 "多態(tài)" 意味著 "多種形式",在編程中,它指的是具有相同名稱的方法/函數(shù)/操作符,可以在許多不同的對象或類上執(zhí)行。

函數(shù)多態(tài)性

一個示例是 Python 中的 len() 函數(shù),它可以用于不同的對象。

字符串

對于字符串,len() 返回字符的數(shù)量:

示例

x = "Hello World!"
print(len(x))

元組

對于元組,len() 返回元組中項的數(shù)量:

示例

mytuple = ("apple", "banana", "cherry")
print(len(mytuple))

字典

對于字典,len() 返回字典中鍵/值對的數(shù)量:

示例

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(len(thisdict))

類的多態(tài)性

多態(tài)性通常在類的方法中使用,其中我們可以具有相同方法名稱的多個類。例如,假設我們有三個類:Car、Boat 和 Plane,它們都有一個名為 move() 的方法:

示例

不同類具有相同的方法:

class Car:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model
  def move(self):
    print("Drive!")
class Boat:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model
  def move(self):
    print("Sail!")
class Plane:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model
  def move(self):
    print("Fly!")
car1 = Car("Ford", "Mustang")       # 創(chuàng)建一個 Car 類
boat1 = Boat("Ibiza", "Touring 20") # 創(chuàng)建一個 Boat 類
plane1 = Plane("Boeing", "747")     # 創(chuàng)建一個 Plane 類
for x in (car1, boat1, plane1):
  x.move()

看看最后的 for 循環(huán)。由于多態(tài)性,我們可以為所有三個類執(zhí)行相同的方法。

繼承類的多態(tài)性

那么具有相同名稱的子類的類呢?我們能在那里使用多態(tài)嗎?如果我們使用上面的示例,并創(chuàng)建一個名為 Vehicle 的父類,并將 Car、Boat 和 Plane 作為 Vehicle 的子類,子類將繼承 Vehicle 的方法,但可以重寫它們:

示例,創(chuàng)建一個名為 Vehicle 的類,使 Car、Boat 和 Plane 成為 Vehicle 的子類:

class Vehicle:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model
  def move(self):
    print("Move!")
class Car(Vehicle):
  pass
class Boat(Vehicle):
  def move(self):
    print("Sail!")
class Plane(Vehicle):
  def move(self):
    print("Fly!")
car1 = Car("Ford", "Mustang") # 創(chuàng)建一個 Car 對象
boat1 = Boat("Ibiza", "Touring 20") # 創(chuàng)建一個 Boat 對象
plane1 = Plane("Boeing", "747") # 創(chuàng)建一個 Plane 對象
for x in (car1, boat1, plane1):
  print(x.brand)
  print(x.model)
  x.move()

到此這篇關(guān)于Python 中多態(tài)性的示例和類的繼承多態(tài)性的文章就介紹到這了,更多相關(guān)Python多態(tài)性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論