python–class
PRATICE
chapter one
利用以下描述餐馆的代码,使Ice-Cream继承之:
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 500
def describe_restaurant(self):
print(f"Our restaurant name is {self.restaurant_name}.")
print(f"Our restaurant cuisine's type is {self.cuisine_type}")
print(f"Right now, about {self.number_served} people eat in there.")
def open_restaurant(self):
print("It's still open now.")
def set_number_served(self, number):
self.number_served += number
添加Ice-Cream的特性后,修改如下所示:
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 500
def describe_restaurant(self):
print(f"Our restaurant name is {self.restaurant_name}.")
print(f"Our restaurant cuisine's type is {self.cuisine_type}")
print(f"Right now, about {self.number_served} people eat in there.")
def open_restaurant(self):
print("It's still open now.")
def set_number_served(self, number):
self.number_served += number
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.flavors = ''
def print_flavors(self):
print(f"My favorite Ice-Cream's flavors is {self.flavors}")
为icecream添加了一个flavors
,并把他设为空字符
调用:
ice_cream = IceCreamStand('KFC', 'EXPENSIVE')
ice_cream.flavors = 'vinilla'
ice_cream.print_flavors()
在稍作修改即可将flavors
储存在一个特定的列表中,并输出之:
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 500
def describe_restaurant(self):
print(f"Our restaurant name is {self.restaurant_name}.")
print(f"Our restaurant cuisine's type is {self.cuisine_type}")
print(f"Right now, about {self.number_served} people eat in there.")
def open_restaurant(self):
print("It's still open now.")
def set_number_served(self, number):
self.number_served += number
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.flavors = []
def append_flavors(self, flavor):
self.flavors.append(flavor)
def print_flavors(self):
print("This is all my favorite flavors: ")
for flavor in self.flavors:
print(f"\tI'd like {flavor.upper()}")
ice_cream = IceCreamStand('KFC', 'EXPENSIVE')
ice_cream.append_flavors('cholocate')
ice_cream.append_flavors('shit')
ice_cream.append_flavors('villina')
ice_cream.append_flavors('strobarry')
ice_cream.print_flavors()
OUTPUT:
>>>
>>>This is all my favorite flavors:
>>> I'd like CHOLOCATE
>>> I'd like SHIT
>>> I'd like VILLINA
>>> I'd like STROBARRY
chapter two:
创建一个类用于管理网络管理员的权限及其输出:
class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0
def describe_user(self):
full_name = f"{self.first_name.title()} {self.last_name.title()}"
print(Full_name)
print(self.login_attempts)
def greet_user(self):
print(f"Hello, {full_name}, It's nice to meet you.")
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
class Admin(User):
def __init__(self, first_name, last_name):
super().__init__(first_name, last_name)
self.privileges = ['can add post', 'can delete post', 'can be user']
self.new_privilege = ''
def print_privileges(self):
print("This all what you can did: ")
for privilege in self.privileges:
print(f"\t{privilege.upper()}")
def change_privileges(self, options):
print("place to enter your options: ")
if options == 'delete':
self.privileges.pop()
elif options == 'append':
self.privileges.append(self.new_privilege)
show_privileges = Admin('Tommy', 'Vercetti')
show_privileges.new_privilege = 'SEXY'
show_privileges.change_privileges('append')
show_privileges.print_privileges()
OUTPUT:
This all what you can did:
CAN ADD POST
CAN DELETE POST
CAN BE USER
SEXY
可以自定义管理员的操作,从而实现对操作的在二次定义。
从文件中导入类:
创建一个模块,里面储存着关于汽车的类,并将文件命名为:car.py
"""一个可用于表示汽车的类。"""
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 100
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name
def read_odometer(self):
print(f"Tis car has {self.odometer_reading} miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("Get the fuck ou off here.")
def increment_odometer(self, miles):
self.odometer_reading += miles
在创建一个模块:my_car.py
利用导入car.py
模块中的类完成一些操作:
from car import Car
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
样例二:
"""car.py"""
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 100
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name
def read_odometer(self):
print(f"Tis car has {self.odometer_reading} miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("Get the fuck ou off here.")
def increment_odometer(self, miles):
self.odometer_reading += miles
class Battery:
def __init__(self, battery_size=75):
self.battery_size = battery_size
def describe_battery(self):
print(f"This car has a {self.battery_size}-KWh battery.")
def get_range(self):
if self.battery_size == 75:
range = 260
elif self.battery_size == 100:
range = 315
print(f"This car can go about {range} miles on a full charge.")
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', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
注解: 当从一个模块中导入很多类时,不推荐使用from module_name import *
语句,因为在导入时没有指明模块中到底倒入了哪些类,所以在命名时容易发生名称之间的冲突或者类之间的名称的冲突,需要从一个模块中导入很多类时,最好使用导入整个模块,并使用句点访问法。