【Python學習記錄——從入門到放棄】八、類(下)
阿新 • • 發佈:2018-12-21
- 給子類定義屬性和方法
class Car(): def __init__(self, make, model, year,odometer_reading=0): self.make = make self.model = model self.year = year self.odometer_reading = odometer_reading def get_descriptive_name(self): long_name = str(self.yesr) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odomter(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def updata_odometer(self, mileage): self.odometer_reading = mileage def increment_odometer(self, miles): self.odometer_reading += miles class ElectricCar(Car): def __init__(self, make, model, year): # ... super(ElectricCar, self).__init__(make, model, year) self.battery_size = 70 def describe_battery(self): print("This car has a " + str(self.battery_size) + "-kWh battery.") my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()
給子類定義屬性和方法其實和建立一個類差不多,該怎麼建立就怎麼建立,繼承只是多了super哪一句還有開始指明父類,來繼承父類的屬性和方法。
- 重寫父類的方法
class Car(): def __init__(self, make, model, year,odometer_reading=0): self.make = make self.model = model self.year = year self.odometer_reading = odometer_reading def get_descriptive_name(self): long_name = str(self.yesr) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odomter(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def updata_odometer(self, mileage): self.odometer_reading = mileage def increment_odometer(self, miles): self.odometer_reading += miles def fill_gas_tank(): print("This car need a gas tank!") class ElectricCar(Car): def __init__(self, make, model, year): # ... super(ElectricCar, self).__init__(make, model, year) def fill_gas_tank(): print("This car doesn't need a gas tank!")
如果你在子類內重新定義父類的方法,當你想要使用這個方法時,那麼程式將會使用你重寫的方法。
- 將例項用作屬性
class Car(): def __init__(self, make, model, year,odometer_reading=0): self.make = make self.model = model self.year = year self.odometer_reading = odometer_reading def get_descriptive_name(self): long_name = str(self.yesr) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odomter(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def updata_odometer(self, mileage): self.odometer_reading = mileage def increment_odometer(self, miles): self.odometer_reading += miles class Battery(): def __init__(self, battery_size=70): self.battery_size = battery_size def describe_battery(self): print("This car has a " + str(self.battery_size) + "-kWh battery.") class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) self.battery = Battery() my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery()
上面這個例子就是把類Battery例項化給類ElectricCar作為屬性。
這樣做的好處就是在屬性和方法過多時,可以使其更加整潔,也容易查詢和修改。
- 模擬實物
這個意思大概是,不能被語法困住,學習程式設計不僅僅只是學習它的語法,更應該學習在程式設計前的思考邏輯,如何能夠快速,方便地解決一個問題,這種思考才是最重要的。
動手試一試:
# 9-6
class Restaurant():
def __init__(self, restaurant_name, restaurant_type):
self.restaurant_name = restaurant_name
self.restaurant_type = restaurant_type
def describe_restaurant(self):
print("\n這家餐廳的名字是:" + self.restaurant_name + "\n這家餐廳的型別是" + self.restaurant_type)
def open_restaurant(self):
print("\n這家餐廳開始營業!")
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, restaurant_type):
super().__init__(restaurant_name, restaurant_type)
self.flavors = []
def add_flavors(self, flavor):
self.flavors.append(flavor)
print('添加了' + flavor + '口味的')
def read_flavors(self):
print('我喜歡的冰淇淋口味有:')
for flavor in self.flavors:
print('\t' + flavor)
my_icecreamstand = IceCreamStand('小小冰淇淋', '冰淇淋店')
my_icecreamstand.add_flavors('抹茶')
my_icecreamstand.add_flavors('香草')
my_icecreamstand.add_flavors('草莓')
my_icecreamstand.read_flavors()
# 9-7
class User():
def __init__(self, first_name, last_name, **kd):
self.first_name = first_name
self.last_name = last_name
self.preperties = {}
for key, value in kd.items():
self.preperties[key] = value
def describe_user(self):
print('\nfirst name: ' + self.first_name + '\nlast name: ' + self.last_name)
for key, value in self.preperties.items():
print(key + ': ' + value + '\n')
class Admin(User):
def __init__(self, first_name, last_name, **kd):
super().__init__(first_name, last_name, **kd)
self.privileges = ['can add post', 'can delete post', 'can ban user']
def show_privileges(self):
print(self.first_name + '所擁有的許可權有:')
for privilege in self.privileges:
print('\t' + privilege)
my_admin = Admin('admin', 'admin')
my_admin.show_privileges()
# 9-8
class User():
def __init__(self, first_name, last_name, **kd):
self.first_name = first_name
self.last_name = last_name
self.preperties = {}
for key, value in kd.items():
self.preperties[key] = value
def describe_user(self):
print('\nfirst name: ' + self.first_name + '\nlast name: ' + self.last_name)
for key, value in self.preperties.items():
print(key + ': ' + value + '\n')
class Privileges():
def __init__(self):
self.privileges = ['can add post', 'can delete post', 'can ban user']
def show_privileges(self):
print('你所擁有的許可權有:')
for privilege in self.privileges:
print('\t' + privilege)
class Admin(User):
def __init__(self, first_name, last_name, **kd):
super().__init__(first_name, last_name, **kd)
self.privileges = Privileges()
my_admin = Admin('admin', 'admin')
my_admin.privileges.show_privileges()
# 9-9
class Car():
def __init__(self, make, model, year,odometer_reading=0):
self.make = make
self.model = model
self.year = year
self.odometer_reading = odometer_reading
def get_descriptive_name(self):
long_name = str(self.yesr) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odomter(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def updata_odometer(self, mileage):
self.odometer_reading = mileage
def increment_odometer(self, miles):
self.odometer_reading += miles
class Battery():
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
def upgrade_battery(self):
if self.battery_size != 85:
self.battery_size = 85
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
四、匯入類
- 匯入單個類
# 這裡儲存在car.py
class Car():
def __init__(self, make, model, year,odometer_reading=0):
self.make = make
self.model = model
self.year = year
self.odometer_reading = odometer_reading
def get_descriptive_name(self):
long_name = str(self.yesr) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odomter(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def updata_odometer(self, mileage):
self.odometer_reading = mileage
def increment_odometer(self, miles):
self.odometer_reading += miles
# 這裡儲存在my_car.py
from car import Car
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car,read_odomter()
- 在一個模組中儲存多個類
# 這是儲存為car.py
class Car():
def __init__(self, make, model, year,odometer_reading=0):
self.make = make
self.model = model
self.year = year
self.odometer_reading = odometer_reading
def get_descriptive_name(self):
long_name = str(self.yesr) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odomter(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def updata_odometer(self, mileage):
self.odometer_reading = mileage
def increment_odometer(self, miles):
self.odometer_reading += miles
class Battery():
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery()
# 這是儲存為my_electric_car.py
from car import ElectricCar
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
- 從一個模組中匯入多個類
這裡儲存在my_cars.py
from car import Car, ElectricCar
my_beetle = Car('Volkswagen', 'beetle', 2016)
print(my_beetle.get_descriptive_name())
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_nameJ())
- 匯入整個模組
import car
my_beetle = car.Car('Volkswagen', 'beetle', 2016)
print(my_beetle.get_descriptive_name())
my_tesla = car.ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_nameJ())
- 匯入模組中的所有類
from car import *
my_beetle = Car('Volkswagen', 'beetle', 2016)
print(my_beetle.get_descriptive_name())
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_nameJ())
- 在一個模組中匯入另一個模組
# 這是儲存為car.py
class Car():
def __init__(self, make, model, year,odometer_reading=0):
self.make = make
self.model = model
self.year = year
self.odometer_reading = odometer_reading
def get_descriptive_name(self):
long_name = str(self.yesr) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odomter(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def updata_odometer(self, mileage):
self.odometer_reading = mileage
def increment_odometer(self, miles):
self.odometer_reading += miles
# 這裡儲存在electric_car.py
from car import Car
class Battery():
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery()
# 這裡儲存在my_cars.py
from car import Car
from electric_car import ElectricCar
my_beetle = Car('Volkswagen', 'beetle', 2016)
print(my_beetle.get_descriptive_name())
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_nameJ())
- 自定義工作流程
233
自定義
把握好每個類
動手試一試:
# 9-10
# 這裡儲存在restaurant.py
class Restaurant():
def __init__(self, restaurant_name, restaurant_type):
self.restaurant_name = restaurant_name
self.restaurant_type = restaurant_type
def describe_restaurant(self):
print("\n這家餐廳的名字是:" + self.restaurant_name + "\n這家餐廳的型別是" + self.restaurant_type)
def open_restaurant(self):
print("\n這家餐廳開始營業!")
# 這裡儲存在my_restaurant.py
from restaurant import Restaurant
my_restaurant = Restaurant('北京烤鴨', '烤鴨店')
your_restaurant = Restaurant('糖醋排骨', '排骨店')
his_restaurant = Restaurant('宮保雞丁', '雞肉店')
my_restaurant.describe_restaurant()
your_restaurant.describe_restaurant()
his_restaurant.describe_restaurant()
# 9-11
# 這裡儲存在users.py
class User():
def __init__(self, first_name, last_name, **kd):
self.first_name = first_name
self.last_name = last_name
self.preperties = {}
for key, value in kd.items():
self.preperties[key] = value
def describe_user(self):
print('\nfirst name: ' + self.first_name + '\nlast name: ' + self.last_name)
for key, value in self.preperties.items():
print(key + ': ' + value + '\n')
class Privileges():
def __init__(self):
self.privileges = ['can add post', 'can delete post', 'can ban user']
def show_privileges(self):
print('你所擁有的許可權有:')
for privilege in self.privileges:
print('\t' + privilege)
class Admin(User):
def __init__(self, first_name, last_name, **kd):
super().__init__(first_name, last_name, **kd)
self.privileges = Privileges()
# 這裡儲存在my_admin.py
from users import Admin
my_admin = Admin('admin', 'admin')
my_admin.privileges.show_privileges()
# 9-11
# 這裡儲存在user.py
class User():
def __init__(self, first_name, last_name, **kd):
self.first_name = first_name
self.last_name = last_name
self.preperties = {}
for key, value in kd.items():
self.preperties[key] = value
def describe_user(self):
print('\nfirst name: ' + self.first_name + '\nlast name: ' + self.last_name)
for key, value in self.preperties.items():
print(key + ': ' + value + '\n')
# 這裡儲存在admin.py
from user import User
class Privileges():
def __init__(self):
self.privileges = ['can add post', 'can delete post', 'can ban user']
def show_privileges(self):
print('你所擁有的許可權有:')
for privilege in self.privileges:
print('\t' + privilege)
class Admin(User):
def __init__(self, first_name, last_name, **kd):
super().__init__(first_name, last_name, **kd)
self.privileges = Privileges()
# 這裡儲存在my_admin.py
from admin import Admin
my_admin = Admin('admin', 'admin')
my_admin.privileges.show_privileges()
五、Python標準庫
Python標準庫是一組Python自帶的模組,可以方便使用者的操作。
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + '.')
動手試一試:
# 9-13
"""
# 6-4的程式碼
types = {
'int':'整數型',
'float':'浮點型',
'boolean':'布林型',
'string':'字串',
'char':'位元組'
}
for key, value in types.items():
print(key + ':' + value)
types['print'] = '列印'
types['if'] = '條件檢測'
types['for'] = '迴圈'
types['[]'] = '列表'
types['{}'] = '字典'
for key, value in types.items():
print(key + ':' + value)
"""
from collections import OrderedDict
types = OrderedDict()
types['int'] = '整數型'
types['float'] = '浮點型'
types['boolean'] = '布林型'
types['string'] = '字串'
types['char'] = '位元組'
for key, value in types.items():
print(key + ':' + value)
types['print'] = '列印'
types['if'] = '條件檢測'
types['for'] = '迴圈'
types['[]'] = '列表'
types['{}'] = '字典'
for key, value in types.items():
print(key + ':' + value)
# 9-14
from random import randint
class Die():
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
print(randint(1, self.sides))
count = 1
six_Die = Die()
while count <= 10:
six_Die.roll_die()
count += 1
count = 1
ten_Die = Die(10)
while count <= 10:
ten_Die.roll_die()
count += 1
count = 1
twenty_Die = Die(20)
while count<=10:
twenty_Die.roll_die()
count += 1
六、類編碼風格
- 駝峰命名法:SixDie(不用下劃線,每個單詞首字母大寫)
- 例項名和模組名都採用小寫格式,單詞與單詞之間用下劃線:six_die
- 每個類和模組要註釋功能文件
- 在類中,使用一個空行來分隔方法;在模組中,使用兩個空行來分隔類
- 匯入模組時,先編寫匯入標準庫的語句,然後用一個空行分隔,接著寫匯入自己編寫的模組的語句。