選單

8.Python類的建立,繼承,匯入

知識點 類的名字要首字母大寫。類由屬性和方法組成。類裡的函式稱為方法。可以用一個類創造多個例項,只要例項名不同即可。類裡面的所有方法都需要self引數。子類可以在super()。

init

()語句的括號中新增新的引數,使子類不僅僅是繼承父類的所有引數。一個模組中可以儲存多個類。1。 建立一個類

class Dog(): #建立一個Dog類,注意首字母大寫和冒號 “”“A simple attempt to model a dog。”“” #docstring def __init__(self, name, age): “”“Initialize name and age attributes。”“” #docstring self。name = name self。age = age def sit(self): “”“Simulate a dog sitting in response to a command。”“” print(self。name。title() + “ is now sitting。”) def roll_over(self): “”“Simulate rolling over in response to a command。”“” print(self。name。title() + “ rolled over!”)

注意:類名要

首字母大寫

類名後面的括號裡面為

,表示這是從零開始建立的類,

沒有繼承

其他類

——init——()

方法較為特殊,用類建立例項時,

自動呼叫

——init——()

方法,其他方法則需要輸入程式碼呼叫 類中的方法必須要有一個

self

引數,且要將

self

引數放在

最前面

——init——()

方法下面定義的變數都要有

self字首

,這樣可以被類中所有的方法呼叫 可以透過例項檢視的變數稱為

屬性

2。 建立一個例項

格式:

例項名=類名(引數)

輸入:

class Dog(): ——-snip——- #Dog類具體細節見上,這=這裡省略 my_dog = Dog(‘willie’, 6) print(“My dog‘s name is ” + my_dog。name。title() + “。”) print(“My dog is ” + str(my_dog。age) + “ years old。”) #數字要轉為字元 my_dog。sit()

輸出:

My dog’s name is Willie。 My dog is 6 years old。 Willie is now sitting。

(1) 獲取屬性

格式:

instance_name。attribute_name

上例中,生成例項時,括號中的‘Willie’一開始還只是一個字串,被作為實參傳送給類中name形參後,被

self。name = name

語句轉換為類的屬性,並使用

my_dog。name

來獲取屬性的值。

(2)呼叫方法

格式:

instance_name。method_name

上例中,當Python讀到

my_dog。sit()

,Python為轉向Dog類,執行裡面的

sit()

方法。

3。 使用類和例項

輸入:

class Car(): “”“A simple attempt to represent a car。”“” def __init__(self, manufacturer, model, year): “”“Initialize attributes to describe a car。”“” self。manufacturer = manufacturer self。model = model self。year = year def get_descriptive_name(self): “”“Return a neatly formatted descriptive name。”“” long_name = str(self。year) + ‘ ’ + self。manufacturer + ‘ ’ + self。model return long_name。title() my_new_car=Car(‘audi’,‘a4’,2016) print(my_new_car。get_descriptive_name())

輸出:

2016 Audi A4

(1) 給屬性設定預設值

在上例的基礎上,新增odometer_reading屬性和read_odometer方法,並將odometer_reading屬性預設值設為0。

輸入:

class Car(): “”“A simple attempt to represent a car。”“” def __init__(self, manufacturer, model, year): “”“Initialize attributes to describe a car。”“” self。manufacturer = manufacturer self。model = model self。year = year self。odometer_reading = 0 #odometer_reading預設值設為0 def get_descriptive_name(self): “”“Return a neatly formatted descriptive name。”“” long_name = str(self。year) + ‘ ’ + self。manufacturer + ‘ ’ + self。model return long_name。title() def read_odometer(self): “”“Print a statement showing the car‘s mileage。”“” print(“This car has ” + str(self。odometer_reading) + “ miles on it。”) my_new_car=Car(’audi‘,’a4‘,2016) print(my_new_car。get_descriptive_name()) my_new_car。read_odometer()

輸出:

2016 Audi A4 This car has 0 miles on it。

(2) 更改預設值1。直接法:

格式:

instance_name。attribute_name = new_value

輸入:

class Car(): ——-snip——- my_new_car=Car(’audi‘,’a4‘,2016) print(my_new_car。get_descriptive_name()) my_new_car。odometer_reading = 23 #更改預設值 my_new_car。read_odometer()

輸出:

2016 Audi A4 This car has 23 miles on it。

2。透過方法更改屬性的值

輸入:

class Car(): ——-snip——- def update_odometer(self, mileage): “”“ Set the odometer reading to the given value。 Reject the change if it attempts to roll the odometer back。 ”“” if mileage >= self。odometer_reading: self。odometer_reading = mileage else: print(“You can’t roll back an odometer!”) my_new_car=Car(‘audi’,‘a4’,2016) print(my_new_car。get_descriptive_name()) my_new_car。update_odometer(300) my_new_car。read_odometer()

透過類裡的update_odometer方法改變屬性的值。需要傳參。

輸出:

2016 Audi A4 This car has 300 miles on it。

4。 繼承

類不一定從零開始建立,一個新類可以從另外一個類中繼承所有的屬性和方法,並且還可以為自己新增新的類和方法。

格式:

class child_class (parent_class)

child_class為子類,parent_class為父類。

(1) 利用繼承建立一個新類

輸入:

class Car(): ——-snip——- class ElectricCar(Car): “”“Models aspects of a car, specific to electric vehicles。”“” def __init__(self, manufacturer, model, year): “”“ Initialize attributes of the parent class。 Then initialize attributes specific to an electric car。 ”“” super()。__init__(manufacturer, model, year) my_tesla = ElectricCar(‘tesla’, ‘roadster’, 2015) print(my_tesla。get_descriptive_name())

輸出:

2015 Tesla Roadster

注意:

__init__

方法接收建立一個Car類所需的所有引數,並且

初始化

Car類。初始化Car類後,

super()

函式

建立父類與子類的連線,讓ElectricCar類

繼承

Car類中所有的方法和屬性,super()。

init

(。。。)語句的括號中,可以新增子類需要的新引數。(2) 為子類新增屬性和方法

可以直接在

super()。__init__(。。。)

語句下面新增子類獨有的屬性。

輸入:

class Car(): ——-snip——- class ElectricCar(Car): “”“Models aspects of a car, specific to electric vehicles。”“” def __init__(self, manufacturer, model, year): “”“ Initialize attributes of the parent class。 Then initialize attributes specific to an electric car。 ”“” super()。__init__(manufacturer, model, year) self。battery_size = 70 #新增新屬性,並且設定預設值 def describe_battery(self): #新增新方法 “”“Print a statement describing the battery size。”“” print(“This car has a ” + str(self。battery_size) + “-kWh battery。”) my_tesla = ElectricCar(‘tesla’, ‘roadster’, 2015) print(my_tesla。get_descriptive_name()) my_tesla。describe_battery()

輸出:

2015 Tesla Roadster This car has a 70-kWh battery。

(3) 重寫父類方法

子類會繼承父類所有的方法和屬性,當某個繼承來的方法需要更改時,我們只需要用和原來方法相同的方法名,重新定義方法。

例如,電動車沒有油箱,所以我們要把ElectricCar類中的fill_gas_tank方法更改一下。

輸入:

class ElectricCar(Car) ——-snip——- def fill_gas_tank(): “”“electric cars don‘t have gas tanks”“” print(“This car doesn’t need a gas tank!”)

這樣,新的fill_gas_tank方法會覆蓋從Car中繼承的fill_gas_tank方法。

(4) 將例項作為屬性

當屬性和方法較多時,可以將一部分屬性和方法分離出來,作為單獨的類。

輸入:

class Car(): ——-snip——- class Battery(): “”“A simple attempt to model a battery for an electric car。”“” def __init__(self, battery_size=60): “”“Initialize the batteery‘s attributes。”“” self。battery_size = battery_size def describe_battery(self): “”“Print a statement describing the battery size。”“” print(“This car has a ” + str(self。battery_size) + “-kWh battery。”) class ElectricCar(Car): “”“Models aspects of a car, specific to electric vehicles。”“” def __init__(self, manufacturer, model, year,battery_size): “”“ Initialize attributes of the parent class。 Then initialize attributes specific to an electric car。 ”“” super()。__init__(manufacturer, model, year) self。battery = Battery(battery_size) my_tesla = ElectricCar(’tesla‘, ’roadster‘, 2015,70) print(my_tesla。get_descriptive_name()) my_tesla。battery。describe_battery()

輸出:

2015 Tesla Roadster This car has a 70-kWh battery。

上例將與電池相關的屬性和方法分離出來,作為一個新類。透過將類Battery的例項作為類ElectricCar的battery屬性,將兩個類關聯起來,雖然類Battery中的引數battery_size預設值為60,卻可以由例項my_tesla的實參改為70。

5。 匯入類

和函式相同,當程式非常複雜時,我們可以將類單獨儲存為一個模組,在主程式的開頭匯入模組即可。

(1)單獨匯入一個類

匯入格式:

from module_name import Class_name

使用格式:

instance_name = Class(arguments) instance_name。attribute instance_name。method(arguments)

(2)匯入多個類

匯入格式:

from module_name import Class1_name,Class2_name,。。。,Classn_name

使用格式:

instance_name = Class(arguments) instance_name。attribute instance_name。method(arguments)

(3)匯入整個模組

匯入格式:

import module_name

使用格式:

instance_name =module_name。Class(arguments) instance_name。attribute instance_name。method(arguments)

只是在用匯入的類生成例項時,需要加上module_name,其他時候不需要。

(4)匯入模組中所有類(不推薦)

匯入格式:

from module_name import *

不推薦這種方法,會弄不清到底使用了哪些類,並且可能造成模組中的類名與主程式的類名衝突。

(5)在一個模組中匯入另一個模組

需要用到繼承時使用,與主程式匯入模組的格式

相同

推薦格式:

from module_name import Class_name